link-solution-easy-to-understand)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// Move operation: O(1)
class TicTacToe {
private int[] rows;
private int[] cols;
private int diagonal;
private int antiDiagonal;
/** Initialize your data structure here. */
public TicTacToe(int n) {
rows = new int[n];
cols = new int[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.
*/
public int move(int row, int col, int player) {
int toAdd = player == 1 ? 1 : -1;
rows[row] += toAdd;
cols[col] += toAdd;
if (row == col) {
diagonal += toAdd;
}
if (col == (cols.length - 1 - row )) {
antiDiagonal += toAdd;
}
int size = rows.length;
if (Math.abs(rows[row]) == size ||
Math.abs(cols[col]) == size ||
Math.abs(diagonal) == size ||
Math.abs(antiDiagonal) == size) {
return player;
}
return 0;
}
}
Brute Force1
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
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74/*
class TicTacToe {
int N;
int[][] checkBoard;
// Initialize your data structure here.
public TicTacToe(int n) {
this.N=n;
checkBoard=new int[n][n];
}
int winner(){
// horizonatal
for(int i=0;i<N;i++){
int count_1=0,count_2=0;
for(int j=0;j<N;j++){
if(checkBoard[i][j]==1) count_1++;
if(checkBoard[i][j]==2) count_2++;
}
if(count_1==N) return 1;
else if(count_2==N) return 2;
}
// vertical
for(int i=0;i<N;i++){
int count_1=0,count_2=0;
for(int j=0;j<N;j++){
if(checkBoard[j][i]==1) count_1++;
if(checkBoard[j][i]==2) count_2++;
}
if(count_1==N) return 1;
else if(count_2==N) return 2;
}
// diagonal
int count_1=0,count_2=0;
for(int i=0;i<N;i++){
if(checkBoard[i][i]==1) count_1++;
if(checkBoard[i][i]==2) count_2++;
}
if(count_1==N) return 1;
else if(count_2==N) return 2;
// anti-diagonal
count_1=0;count_2=0;
for(int i=0;i<N;i++){
if(checkBoard[i][N-1-i]==1) count_1++;
if(checkBoard[i][N-1-i]==2) count_2++;
}
if(count_1==N) return 1;
else if(count_2==N) return 2;
return 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 move(int row, int col, int player) {
checkBoard[row][col]=player;
return winner();
}
}*/
/**
* Your TicTacToe object will be instantiated and called as such:
* TicTacToe obj = new TicTacToe(n);
* int param_1 = obj.move(row,col,player);
*/