Java O(n) solution - a better first step than O(n^2)


  • 0
    A
    public class TicTacToe {
        int[][] board;
        int n;
        
        /** Initialize your data structure here. */
        public TicTacToe(int n) {
            this.n = n;
            board = new int[n][n]; 
            for(int i =0 ;i < n;i++){
                for(int j = 0;j<n;j++){
                    board[i][j] = 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) {
            int rowCount = 0, columnCount = 0, diagleft = 0,diagright = 0;
             board[row][col] = player;
            for(int i =0;i<n;i++){
                if(board[row][i] == player){
                    rowCount++;
                }
            }
            for(int i =0;i<n;i++){
                  if(board[i][col] == player){
                    columnCount++;
                }
            }
            for(int i =0 ;i<n;i++){
                 if(board[i][i] == player){
                   diagleft++;
                 }
            }
            
            int j = 0;
            for(int i = n-1;i>=0;i--){
                if(board[j][i] == player ){
                    diagright++;
                }
                j++;
            }
           
            if(rowCount == n || columnCount == n || diagleft == n || diagright == n ){
                return player;
            }else {
                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.