Correct solution


  • 0
    A

    class TicTacToe {

    /** Initialize your data structure here. */
    public int[][] table;
    public TicTacToe(int n) {
        table = new int[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(table[row][col] == 0){
            table[row][col] = player;
        }
        int winner = 0;
        
        if(verticalWin(row, col, player) || horizontalWin(row, col, player) || diagonalWin(row, col, player)){
            winner = player;
        }
        
        return winner;
    }
    
    public boolean verticalWin(int row, int col, int player){
        for(int i = 0 ; i < table.length; i++){
            if(table[i][col] != player){
                return false;
            }
        }
        return true;
    }
    
    public boolean horizontalWin(int row, int col, int player){
        
        for(int i = 0 ; i < table.length; i++){
            if(table[row][i] != player){
                return false;
            }
        }
        return true;
    }
    
    public boolean diagonalWin(int row, int col, int player){
        int counter = 0;
        boolean ret = false;
        for(int i = 0 ; i < table.length; i++){
            if(table[i][i] != player){
            	counter++;
            }
        }
        if(counter == 0){
            return true;
        }
        
        int counter2 = 0;
        for(int i = table.length - 1; i >= 0; i-- ){
        	if(table[i][table.length - 1 - i] != player){
        		counter2++;
        	}
        }
        if(counter2 == 0){
        	return true;
        }
        return false;
    }
    

    }


Log in to reply
 

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