0%

348. Design Tic-Tac-Toe

O(1) time O(n) space

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
class TicTacToe {
public:
/** Initialize your data structure here. */
TicTacToe(int n) : n(n) {
v.resize(n);
h.resize(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. */
int move(int row, int col, int player) {
int s = (player << 1) - 3;
if (abs(h[row] += s) == n) return player;
if (abs(v[col] += s) == n) return player;
if (abs(d += (row == col) * s) == n) return player;
if (abs(ad += (row + col == n - 1) * s) == n) return player;
return 0;
}

int n;
vector<int> v, h;
int d = 0, ad = 0;
};

/**
* Your TicTacToe object will be instantiated and called as such:
* TicTacToe* obj = new TicTacToe(n);
* int param_1 = obj->move(row,col,player);
*/