-
Notifications
You must be signed in to change notification settings - Fork 3
Expand file tree
/
Copy pathLeetCode-348-Design-Tic-Tac-Toe.java
More file actions
117 lines (95 loc) · 2.89 KB
/
LeetCode-348-Design-Tic-Tac-Toe.java
File metadata and controls
117 lines (95 loc) · 2.89 KB
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
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
class TicTacToe {
// int[][] board;
// int n;
// /** Initialize your data structure here. */
// public TicTacToe(int n) {
// this.board = new int[n][n];
// this.n = 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. */
/*
Time: O(N^2)
*/
// public int move(int row, int col, int player) {
// board[row][col] = player;
// boolean vertical = true;
// for (int i = 0; i < n; i++) {
// if (board[i][col] != player) {
// vertical = false;
// break;
// }
// }
// if (vertical) return player;
// boolean horizontal = true;
// for (int j = 0; j < n; j++) {
// if (board[row][j] != player) {
// horizontal = false;
// break;
// }
// }
// if (horizontal) return player;
// if (row == col || row + col == n - 1) {
// boolean diag = true;
// for (int i = 0; i < n; i++) {
// if (board[i][i] != player) {
// diag = false;
// break;
// }
// }
// if (diag) return player;
// diag = true;
// for (int i = 0; i < n; i++) {
// if (board[i][n - i - 1] != player) {
// diag = false;
// break;
// }
// }
// if (diag) return player;
// }
// return 0;
// }
int[] rows;
int[] cols;
int diag;
int antiDiag;
int n;
/** Initialize your data structure here. */
public TicTacToe(int n) {
this.rows = new int[n];
this.cols = new int[n];
this.diag = 0;
this.antiDiag = 0;
this.n = n;
}
/*
Time: O(1)
Space: O(N)
*/
public int move(int row, int col, int player) {
int toAdd = player == 1 ? 1 : -1;
rows[row] += toAdd;
cols[col] += toAdd;
if (row == col) {
diag += toAdd;
}
if (row == n - col - 1) {
antiDiag += toAdd;
}
if (Math.abs(rows[row]) == n || Math.abs(cols[col]) == n || Math.abs(diag) == n || Math.abs(antiDiag) == n) {
return player;
}
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);
*/