7 Line Java Move Implementation O(1)


  • 0
    J
    public class TicTacToe {
    
        /** Initialize your data structure here. */
        int[][] grid;   
        int size;
        
        int[][] playerRowCounts;
        int[][] playerColCounts;
        int[][] playerDiagCounts;    
        int[] playerMax;
     
        public TicTacToe(int n) {
            grid = new int[n][n];
            size = n;
            playerRowCounts = new int[2][size];
            playerColCounts = new int[2][size];
            playerDiagCounts =  new int[2][2];
            playerMax = new int[2];
            
        }
        
        /** 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) {
            grid[row][col] = player;
            playerMax[player-1] = Math.max(playerMax[player-1],++playerRowCounts[player-1][col]);
            playerMax[player-1] = Math.max(playerMax[player-1],++playerColCounts[player-1][row]);
            if(row==col) playerMax[player-1] = Math.max(playerMax[player-1],++playerDiagCounts[player-1][0]);
            if(size - 1 - row == col) playerMax[player-1] = Math.max(playerMax[player-1],++playerDiagCounts[player-1][1]);
            if(playerMax[player-1] == size) return player;
            return 0;    
        }
            
    }
    

Log in to reply
 

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