05 August 2008
Design a Tic-tac-toe game that is played between two players on a n x n grid.
You may assume the following rules:
Example:
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
36
37
38
Given n = 3, assume that player 1 is "X" and player 2 is "O" in the board.
TicTacToe toe = new TicTacToe(3);
toe.move(0, 0, 1); -> Returns 0 (no one wins)
|X| | |
| | | | // Player 1 makes a move at (0, 0).
| | | |
toe.move(0, 2, 2); -> Returns 0 (no one wins)
|X| |O|
| | | | // Player 2 makes a move at (0, 2).
| | | |
toe.move(2, 2, 1); -> Returns 0 (no one wins)
|X| |O|
| | | | // Player 1 makes a move at (2, 2).
| | |X|
toe.move(1, 1, 2); -> Returns 0 (no one wins)
|X| |O|
| |O| | // Player 2 makes a move at (1, 1).
| | |X|
toe.move(2, 0, 1); -> Returns 0 (no one wins)
|X| |O|
| |O| | // Player 1 makes a move at (2, 0).
|X| |X|
toe.move(1, 0, 2); -> Returns 0 (no one wins)
|X| |O|
|O|O| | // Player 2 makes a move at (1, 0).
|X| |X|
toe.move(2, 1, 1); -> Returns 1 (player 1 wins)
|X| |O|
|O|O| | // Player 1 makes a move at (2, 1).
|X|X|X|
Follow up:
Could you do better than O(n2) per
operation?1
move()
1) 绘制棋盘,判断当前落子所在行与列是否都是该棋手的子,以及如果落子在对角线上,则同时需要判断对角线上的子是否都是该棋手的子。
2) 不需要复现棋盘,只需要计算每个player在各条线是否放了n个棋子就能知道是否获胜。 不用二维数组,近一步减小空间消耗,+1计算player1的棋子数,-1计算player2的棋子数,只要有一方达到边界就算赢(n-1,player1赢,1-n,player2赢)。时间O(1),空间O(n)。
方法1
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
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
class TicTacToe {
private int[][] scope;
public TicTacToe(int n) {
scope = new int[n][n];
}
public int move(int row, int col, int player) {
scope[row][col] = player;
// 横
boolean win = true;
for (int item : scope[row]) {
if (item != player) {
win = false;
break;
}
}
if (win) {
return player;
}
// 竖
win = true;
for (int i = 0; i < scope.length; i++) {
if (scope[i][col] != player) {
win = false;
break;
}
}
if (win) {
return player;
}
// 左对角
win = true;
for (int i = 0; i < scope.length; i++) {
if (scope[i][i] != player) {
win = false;
break;
}
}
if (win) {
return player;
}
// 有对角
win = true;
for (int i = 0; i < scope.length; i++) {
if (scope[i][scope.length - 1 - i] != player) {
win = false;
break;
}
}
if (win) {
return player;
} else {
return 0;
}
}
}
方法2
1
2
3
4
5
6
7
8
9
10
11
12
13
class TicTacToe {
int[] rows, cols, dig;
int n;
public TicTacToe(int n) {
rows = new int[n];
cols = new int[n];
dig = new int[2];
this.n = n;
}
public int move(int row, int col, int player) {
return ((player == 1 && rows[row]++ == n-1 | cols[col]++ == n-1 | (row == col && dig[0]++ == n-1) | (row + col == n-1 && dig[1]++ == n-1)) || (player == 2 && rows[row]-- == 1-n | cols[col]-- == 1-n | (row == col && dig[0]-- == 1-n) | (row + col == n-1 && dig[1]-- == 1-n))) ? player : 0;
}
}