O(1) JAVA Solution Short And Easy


  • 0
    Y
    public class TicTacToe {
        int anti_diagonal;
        int diagonal;
        int[] rows;
        int[] cols;
        int n;
        /** Initialize your data structure here. */
        public TicTacToe(int n) {
            rows = new int[n];
            cols = new int[n];
            this.n = 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) {
            if(row == col)
                diagonal = player == 1 ? diagonal + 1 : diagonal - 1;
            if(row + col == n - 1)
                anti_diagonal = player == 1 ? anti_diagonal + 1 : anti_diagonal - 1;
            rows[row] = player == 1 ? rows[row] + 1 : rows[row] - 1;
            cols[col] = player == 1 ? cols[col] + 1 : cols[col] - 1;
            return player == 1 ? ((rows[row] == n || cols[col] == n || diagonal == n || anti_diagonal == n) ? 1 : 0)
                    : ((rows[row] == -n || cols[col] == -n || diagonal == -n || anti_diagonal == -n) ? 2 : 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.