Design a Tic-tac-toe game that is played between two players on anxngrid.
You may assume the following rules:
- A move is guaranteed to be valid and is placed on an empty block.
- Once a winning condition is reached, no more moves is allowed.
- A player who succeeds in placing n of their marks in a horizontal, vertical, or diagonal row wins the game.
class TicTacToe {
private int[][] matrix;
/** Initialize your data structure here. */
public TicTacToe(int n) {
this.matrix = 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) {
matrix[row][col] = player;
if(checkRow(row, player))
return player;
if(checkCol(col, player))
return player;
if(checkDiag(player))
return player;
return 0;
}
private boolean checkRow(int row, int player) {
boolean won = true;
for(int i = 0; i < matrix.length; i++) {
if(matrix[row][i] != player) {
won = false;
break;
}
}
return won;
}
private boolean checkCol(int col, int player) {
boolean won = true;
for(int i = 0; i < matrix.length; i++) {
if(matrix[i][col] != player) {
won = false;
break;
}
}
return won;
}
private boolean checkDiag(int player) {
boolean won = true;
for(int i = 0; i < matrix.length; i++) {
if(matrix[i][i] != player) {
won = false;
break;
}
}
if(won)
return won;
won = true;
for(int i = 0; i < matrix.length; i++) {
if(matrix[matrix.length - 1 - i][i] != player) {
won = false;
break;
}
}
return won;
}
}
/**
* Your TicTacToe object will be instantiated and called as such:
* TicTacToe obj = new TicTacToe(n);
* int param_1 = obj.move(row,col,player);
*/