Easy to understand Java O(1) time move


  • 0
    T
    public class TicTacToe {
    int[] rows;
    int []cols;
    int size;
    int diag1;
    int diag2;
    /** Initialize your data structure here. */
    public TicTacToe(int n) {
        rows = new int[n];
        cols = new int[n];
        size = n;
        diag1 = 0;
        diag2 = 0;
    }
    
    /** 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) {
        if(player==1){
            rows[row]+=1;
            cols[col]+=1;
            if(row == col) diag1++;
            if(row+col == size-1) diag2++;
            
            if(rows[row] == size || cols[col] == size || diag1 == size || diag2 == size) return 1;
        }else{
            rows[row]-=1;
            cols[col]-=1;
            if(row == col) diag1--;
            if(row+col == size-1) diag2--;
            if(Math.abs(rows[row]) == size || Math.abs(cols[col]) == size || Math.abs(diag1) == size || Math.abs(diag2) == size) return 2;
        }
        
        return 0;
    }
    

    }

    /**

    • Your TicTacToe object will be instantiated and called as such:
    • TicTacToe obj = new TicTacToe(n);
    • int param_1 = obj.move(row,col,player);
      */

Log in to reply
 

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