JAVA O(1) Short Code


  • 0
    L
    class TicTacToe {
        private int[][] rows, cols;
        private int[] diag1, diag2;
        private int win = 0, n = 0;
        /** Initialize your data structure here. */
        public TicTacToe(int n) {
            this.n = n;
            this.win = 0;
            diag1 = new int[2];
            diag2 = new int[2];
            rows = new int[2][n];
            cols = new int[2][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(win != 0) return win;
            if(++rows[player - 1][row] == n) win = player;
            if(++cols[player - 1][col] == n) win = player;
            if(row == col && ++diag1[player - 1] == n) win = player;
            if(row + col == n - 1 && ++diag2[player - 1] == n) win = player;
            return win;
        }
    }
    
    

Log in to reply
 

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