题目地址:
https://leetcode.com/problems/design-tic-tac-toe/
给定一个方阵,两个人玩游戏,每个人可以在某个方格填上带有自己标记的记号。如果有某一行或者某一列或者某个对角线(指的是最长的两条对角线)全标记了相同的记号,则判定那个玩家获胜。
要求设计这个类,里面提供初始化和move方法,move方法的三个参数分别为行、列、玩家编号( 1 1 1或者 2 2 2)。如果其中一个玩家在走完当前步的时候会获胜,则返回他的编号;否则返回 0 0 0。
思路是将玩家编号映射到 − 1 -1 −1和 1 1 1,然后每次走的时候,就将其所在行、列、对角线记录的数值加上 − 1 -1 −1或者 1 1 1。这样一个玩家获胜当且仅当某个行、列、对角线记录的数字刚好等于 n n n或者 − n -n −n。代码如下:
class TicTacToe {
private:
vector<int> rows, cols;
int diag, antidiag;
int size;
public:
TicTacToe(int n) : rows(n, 0), cols(n, 0), diag(0), antidiag(0), size(n) {}
int move(int row, int col, int player) {
int add = player * 2 - 3;
rows[row] += add;
cols[col] += add;
if (row == col) diag += add;
if (row + col == size - 1) antidiag += add;
if (rows[row] == size || cols[col] == size || diag == size ||
antidiag == size)
return 2;
else if (rows[row] == -size || cols[col] == -size || diag == -size ||
antidiag == -size)
return 1;
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);
*/
时间复杂度 O ( 1 ) O(1) O(1),空间 O ( n ) O(n) O(n), n n n为矩阵边长。