Check if board is a valid TTT state.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
Example 1:
Input: board = ["O ", " ", " "]
Output: false
Explanation: The first player always plays "X".

Example 2:
Input: board = ["XOX", " X ", " "]
Output: false
Explanation: Players take turns making moves.

Example 3:
Input: board = ["XXX", " ", "OOO"]
Output: false

Example 4:
Input: board = ["XOX", "O O", "XOX"]
Output: true

Note:

  • board is a length-3 array of strings, where each string board[i] has length 3.
  • Each board[i][j] is a character in the set {" ", "X", "O"}.
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
public boolean validTicTacToe(String[] board) {
int[] rows = new int[3];
int[] cols = new int[3];
int diagonal = 0;
int antidiagonal = 0;
int turns = 0;
boolean xwin = false;
boolean owin = false;

for (int i = 0; i < 3; ++i) {
for (int j = 0; j < 3; ++j) {
if (board[i].charAt(j) == 'X') {
turns++; rows[i]++; cols[j]++;
if (i == j) diagonal++;
if (i + j == 2) antidiagonal++;
}
else if (board[i].charAt(j) == 'O') {
turns--; rows[i]--; cols[j]--;
if (i == j) diagonal--;
if (i + j == 2) antidiagonal--;
}
}
}

xwin = rows[0] == 3 || rows[1] == 3 || rows[2] == 3 ||
cols[0] == 3 || cols[1] == 3 || cols[2] == 3 ||
diagonal == 3 || antidiagonal == 3;

owin = rows[0] == -3 || rows[1] == -3 || rows[2] == -3 ||
cols[0] == -3 || cols[1] == -3 || cols[2] == -3 ||
diagonal == -3 || antidiagonal == -3;

// player1/2 win: his last turn
if (xwin && turns == 0 || owin && turns == 1) return false;

// turns must be 0/1; two players cannot win same time
return (turns == 1 || turns == 0) && (!xwin || !owin);
}