-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy path1275-FindWinnerOnATicTacToeGame.java
More file actions
54 lines (46 loc) · 1.48 KB
/
Copy path1275-FindWinnerOnATicTacToeGame.java
File metadata and controls
54 lines (46 loc) · 1.48 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
class Solution {
public String tictactoe(int[][] moves) {
String[][] board = new String[3][3];
for (String[] row : board)
Arrays.fill(row, "E");
int player = 0;
for (int[] move : moves) {
if (player == 0) {
board[move[0]][move[1]] = "A";
player += 1;
} else {
board[move[0]][move[1]] = "B";
player -= 1;
}
}
// check rows
for (int i = 0; i < 3; i++) {
if (board[i][0] != "E") {
if (board[i][0].equals(board[i][1]) && board[i][1].equals(board[i][2])) {
return board[i][0];
}
}
}
// check columns
for (int j = 0; j < 3; j++) {
if (board[0][j] != "E") {
if (board[0][j].equals(board[1][j]) && board[1][j].equals(board[2][j])) {
return board[0][j];
}
}
}
// check diagonal from top left
if (board[0][0] != "E") {
if (board[0][0].equals(board[1][1]) && board[1][1].equals(board[2][2])) {
return board[0][0];
}
}
// check diagonal from top right
if (board[0][2] != "E") {
if (board[0][2].equals(board[1][1]) && board[1][1].equals(board[2][0])) {
return board[0][2];
}
}
return moves.length == 9 ? "Draw" : "Pending";
}
}