Google
348 Design Tic-Tac-Toe

1. Question

Design a Tic-tac-toe game that is played between two players on anxngrid.
You may assume the following rules:
  1. 1.
    A move is guaranteed to be valid and is placed on an empty block.
  2. 2.
    Once a winning condition is reached, no more moves is allowed.
  3. 3.
    A player who succeeds in placing n of their marks in a horizontal, vertical, or diagonal row wins the game.
Example:
1
Given n = 3, assume that player 1 is "X" and player 2 is "O" in the board.
2
3
TicTacToe toe = new TicTacToe(3);
4
5
toe.move(0, 0, 1); -> Returns 0 (no one wins)
6
|X| | |
7
| | | | // Player 1 makes a move at (0, 0).
8
| | | |
9
10
toe.move(0, 2, 2); -> Returns 0 (no one wins)
11
|X| |O|
12
| | | | // Player 2 makes a move at (0, 2).
13
| | | |
14
15
toe.move(2, 2, 1); -> Returns 0 (no one wins)
16
|X| |O|
17
| | | | // Player 1 makes a move at (2, 2).
18
| | |X|
19
20
toe.move(1, 1, 2); -> Returns 0 (no one wins)
21
|X| |O|
22
| |O| | // Player 2 makes a move at (1, 1).
23
| | |X|
24
25
toe.move(2, 0, 1); -> Returns 0 (no one wins)
26
|X| |O|
27
| |O| | // Player 1 makes a move at (2, 0).
28
|X| |X|
29
30
toe.move(1, 0, 2); -> Returns 0 (no one wins)
31
|X| |O|
32
|O|O| | // Player 2 makes a move at (1, 0).
33
|X| |X|
34
35
toe.move(2, 1, 1); -> Returns 1 (player 1 wins)
36
|X| |O|
37
|O|O| | // Player 1 makes a move at (2, 1).
38
|X|X|X|
Copied!
Follow up: Could you do better than O(n2) permove()operation?

2. Implementation

1
class TicTacToe {
2
int[] rows;
3
int[] cols;
4
int diagnol;
5
int antiDiagnol;
6
int n;
7
8
/** Initialize your data structure here. */
9
public TicTacToe(int n) {
10
rows = new int[n];
11
cols = new int[n];
12
this.n = n;
13
}
14
15
/** Player {player} makes a move at ({row}, {col}).
16
@param row The row of the board.
17
@param col The column of the board.
18
@param player The player, can be either 1 or 2.
19
@return The current winning condition, can be either:
20
0: No one wins.
21
1: Player 1 wins.
22
2: Player 2 wins. */
23
public int move(int row, int col, int player) {
24
int toAdd = player == 1 ? 1 : -1;
25
26
rows[row] += toAdd;
27
cols[col] += toAdd;
28
if (row == col) {
29
diagnol += toAdd;
30
}
31
32
if (col == n - row - 1) {
33
antiDiagnol += toAdd;
34
}
35
36
if (Math.abs(rows[row]) == n || Math.abs(cols[col]) == n
37
|| Math.abs(diagnol) == n || Math.abs(antiDiagnol) == n) {
38
return player;
39
}
40
return 0;
41
}
42
}
43
44
/**
45
* Your TicTacToe object will be instantiated and called as such:
46
* TicTacToe obj = new TicTacToe(n);
47
* int param_1 = obj.move(row,col,player);
48
*/
Copied!

3. Time & Space Complexity

move(): 时间复杂度O(1), 空间复杂度O(n)