LeetCode 348. 【Java】348. Design Tic-Tac-Toe
原题链接
中等
作者:
tt2767
,
2020-03-30 17:43:06
,
所有人可见
,
阅读 824
/**
1. 同一行、同一列或者同一斜对角线上都放置了自己的棋子,那么他便获得胜利 -> 只需要一维全满即可成功 -> 降维处理 -> 每个变量代表一维, 1++, 2--
2. 如果任意一个值改变后为 n -> 1win , -n->2win, otherEnd->0 noWin
*/
class TicTacToe {
/** Initialize your data structure here. */
int size, ldig, rdig;
int[] rows, cols;
public TicTacToe(int n) {
size = n;
rows = new int[n];
cols = new int[n];
Arrays.fill(rows, 0);
Arrays.fill(cols, 0);
ldig = 0;
rdig = 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 check(int value){
if (value == size || value == -size) return value > 0 ? 1 : 2;
return 0;
}
public int move(int row, int col, int player) {
int res = 0;
rows[row] += player == 1 ? 1 : -1;
res = check(rows[row]);
if (res != 0) return res;
cols[col] += player == 1? 1 : -1;
res = check(cols[col]);
if (res != 0) return res;
if (row == col) {
ldig += player == 1 ? 1 : -1;
res = check(ldig);
if (res != 0) return res;
}
if (row + col == size-1) {
rdig += player == 1 ? 1: -1;
res = check(rdig);
if (res != 0) return res;
}
return res;
}
}
/**
* Your TicTacToe object will be instantiated and called as such:
* TicTacToe obj = new TicTacToe(n);
* int param_1 = obj.move(row,col,player);
*/