Solution URL
https://leetcode-cn.com/submissions/detail/120265439/
代码
class TicTacToe {
//ans: https://leetcode-cn.com/problems/design-tic-tac-toe/solution/348-pan-ding-jing-zi-qi-sheng-fu-by-klb/
private int n;
private int[] rows;
private int[] cols;
private int[] diags;
/** Initialize your data structure here. */
public TicTacToe(int n) {
//use array to store the state of every row, col and diagnose
rows = new int[n];
cols = new int[n];
//there are two diagnose
diags = new int[2];
this.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) {
boolean isWin = false;
//if player 1
if(player == 1){
//for the input, self-increasing corresponding row, col and diag
rows[row]++;
cols[col]++;
if(row == col) diags[0]++;
if(row + col == n - 1) diags[1]++;
//check whether player is win in row or col or diag
isWin = (rows[row] == n ) ||
(cols[col] == n) ||
((row == col) && diags[0] == n) ||
((row + col == n - 1) && diags[1] == n);
if(isWin) return player;
else return 0;
}else{
//for the input, self-decreasing corresponding row, col and diag
rows[row]--;
cols[col]--;
if(row == col) diags[0]--;
if(row + col == n - 1) diags[1]--;
//check whether player is win in row or col or diag
isWin = (rows[row] == -n ) ||
(cols[col] == -n) ||
((row == col) && diags[0] == -n) ||
((row + col == n - 1) && diags[1] == -n);
if(isWin) 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);
*/