Skip to content

Commit a32f72b

Browse files
committed
Modified Find Winner on a Tic Tac Toe Game.java
1 parent 5622751 commit a32f72b

File tree

1 file changed

+33
-44
lines changed

1 file changed

+33
-44
lines changed
Lines changed: 33 additions & 44 deletions
Original file line numberDiff line numberDiff line change
@@ -1,49 +1,38 @@
11
class Solution {
2-
int[] rowCount;
3-
int[] colCount;
4-
int[] diagCount;
5-
public String tictactoe(int[][] moves) {
6-
rowCount = new int[3];
7-
colCount = new int[3];
8-
diagCount = new int[2];
9-
int numOfMoves = 0;
10-
for (int i = 0; i < moves.length; i++) {
11-
int x = moves[i][0];
12-
int y = moves[i][1];
13-
int move = i % 2 == 0 ? 1 : -1;
14-
updateBoard(x, y, move);
15-
numOfMoves++;
16-
if (checkForWinner(x, y)) {
17-
return i % 2 == 0 ? "A" : "B";
18-
}
2+
public String tictactoe(int[][] moves) {
3+
int n = 3;
4+
Map<Integer, Map<Character, Integer>> rowMap = new HashMap<>();
5+
Map<Integer, Map<Character, Integer>> colMap = new HashMap<>();
6+
Map<Character, Integer> rightDiagMap = new HashMap<>();
7+
Map<Character, Integer> leftDiagMap = new HashMap<>();
8+
for (int i = 0; i < moves.length; i++) {
9+
int x = moves[i][0];
10+
int y = moves[i][1];
11+
char move = i % 2 == 0 ? 'X' : 'O';
12+
String player = i % 2 == 0 ? "A" : "B";
13+
Map<Character, Integer> row = rowMap.computeIfAbsent(x, k -> new HashMap<>());
14+
row.put(move, row.getOrDefault(move, 0) + 1);
15+
if (row.get(move) == 3) {
16+
return player;
17+
}
18+
Map<Character, Integer> col = colMap.computeIfAbsent(y, k -> new HashMap<>());
19+
col.put(move, col.getOrDefault(move, 0) + 1);
20+
if (col.get(move) == 3) {
21+
return player;
22+
}
23+
if (x == y) {
24+
leftDiagMap.put(move, leftDiagMap.getOrDefault(move, 0) + 1);
25+
if (leftDiagMap.get(move) == 3) {
26+
return player;
1927
}
20-
return numOfMoves == 9 ? "Draw" : "Pending";
21-
}
22-
23-
private boolean checkForWinner(int x, int y) {
24-
if (rowCount[x] == 3 || rowCount[x] == -3) {
25-
return true;
26-
}
27-
if (colCount[y] == 3 || colCount[y] == -3) {
28-
return true;
29-
}
30-
if (x == y && (diagCount[0] == 3 || diagCount[0] == -3)) {
31-
return true;
32-
}
33-
if (x + y == 2 && (diagCount[1] == 3 || diagCount[1] == -3)) {
34-
return true;
35-
}
36-
return false;
37-
}
38-
39-
private void updateBoard(int x, int y, int move) {
40-
rowCount[x] += move;
41-
colCount[y] += move;
42-
if (x == y) {
43-
diagCount[0] += move;
44-
}
45-
if (x + y == 2) {
46-
diagCount[1] += move;
28+
}
29+
if (x + y == n - 1) {
30+
rightDiagMap.put(move, rightDiagMap.getOrDefault(move, 0) + 1);
31+
if (rightDiagMap.get(move) == 3) {
32+
return player;
4733
}
34+
}
4835
}
36+
return moves.length == n * n ? "Draw" : "Pending";
37+
}
4938
}

0 commit comments

Comments
 (0)