Java straight forward solution, inspired by the hint


  • 0

    The solution is inspired by the hint. Hope it helps.
    Any comment is welcomed.

        int[] rows;
        int[] cols;
        int diagonal;
        int antiDiagonal;
        int size;
        /** Initialize your data structure here. */
        public TicTacToe(int n) {
            this.rows = new int[n];
            this.cols = new int[n];
            this.diagonal = 0;
            this.antiDiagonal = 0;
            this.size = n;
        }
        
        /** Player {player} makes a move at ({row}, {col}).
            @param row The row of the board.
            @param col The column of the board.
            @param player The player, can be either 1 or 2.
            @return The current winning condition, can be either:
                    0: No one wins.
                    1: Player 1 wins.
                    2: Player 2 wins. */
        public int move(int row, int col, int player) {
            // updating the rows and cols array, the value stored in each rows[i] or cols[i] 
            //denotes the sum of values in current row or col
            rows[row] += (player == 1) ? 1 : -1;
            if(rows[row] == size) return 1;
            if(rows[row] == -size) return 2;
            cols[col] += (player == 1) ? 1 : -1;
            if(cols[col] == size) return 1;
            if(cols[col] == -size) return 2;
            
            // Similar to rows or cols
            if(row == col)
                diagonal += (player == 1) ? 1 : -1;
            if(diagonal == size)
                return 1;
            if(diagonal == -size)
                return 2;
            
            if(row + col == size - 1)
                antiDiagonal += (player == 1) ? 1 : -1;
            if(antiDiagonal == size)
                return 1;
            if(antiDiagonal == -size)
                return 2;
                
            return 0;
        }
    

  • 0

    Thank you for your code. But I'm a little confused about hte

       rows[row] += (player == 1) ? 1 : -1;
       if(rows[row] == size) return 1;
       if(rows[row] == -size) return 2;
    

    and the antiDiagonal part. Could someone please pick one to explain?


Log in to reply
 

Looks like your connection to LeetCode Discuss was lost, please wait while we try to reconnect.