Skip to content

Commit 60a0a67

Browse files
find winner on a tic tac toe game
1 parent c003d4d commit 60a0a67

File tree

2 files changed

+36
-2
lines changed

2 files changed

+36
-2
lines changed

README.md

+2-2
Original file line numberDiff line numberDiff line change
@@ -328,8 +328,8 @@
328328
| 1252 | [Cells With Odd Values In Matrix](https://leetcode.com/problems/cells-with-odd-values-in-a-matrix) | [![Java](assets/java.png)](src/CellsWithOddValuesInMatrix.java) | |
329329
| 1260 | [Shift 2D Grid](https://leetcode.com/problems/shift-2d-grid) | [![Java](assets/java.png)](src/Shift2DGrid.java) | |
330330
| 1266 | [Minimum Time Visiting All Points](https://leetcode.com/problems/minimum-time-visiting-all-points) | [![Java](assets/java.png)](src/MinimumTimeVisitingAllPoints.java) | |
331-
| 1271 | [Hexspeak](https://leetcode.com/problems/hexspeak) | | |
332-
| 1275 | [Find Winner On a Tic Tac Toe Game](https://leetcode.com/problems/find-winner-on-a-tic-tac-toe-game) | | |
331+
| 1271 | 🔒 [Hexspeak](https://leetcode.com/problems/hexspeak) | | |
332+
| 1275 | [Find Winner On a Tic Tac Toe Game](https://leetcode.com/problems/find-winner-on-a-tic-tac-toe-game) | [![Java](assets/java.png)](src/FindWinnerOnATicTacToeGame.java) | |
333333
| 1281 | [Subtract the Product and Sum of Digits of a Integer](https://leetcode.com/problems/subtract-the-product-and-sum-of-digits-of-an-integer) | | |
334334
| 1287 | [Element Appearing More Than 25% in Sorted Array](https://leetcode.com/problems/element-appearing-more-than-25-in-sorted-array) | | |
335335
| 1290 | [Convert Binary Number In A Linked List to Integer](https://leetcode.com/problems/convert-binary-number-in-a-linked-list-to-integer) | | |

src/FindWinnerOnATicTacToeGame.java

+34
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,34 @@
1+
public class FindWinnerOnATicTacToeGame {
2+
public String tictactoe(int[][] moves) {
3+
String winner = getWinnerInTicTacToe(moves);
4+
if ("".equals(winner)) return moves.length == 9 ? "Draw" : "Pending";
5+
return winner;
6+
}
7+
8+
private String getWinnerInTicTacToe(int[][] moves) {
9+
final int[] rows = new int[3], columns = new int[3];
10+
int d1 = 0, d2 = 0, k = 1;
11+
for (int[] move : moves) {
12+
rows[move[0]] += k;
13+
columns[move[1]] += k;
14+
if (move[0] == move[1]) d1 += k;
15+
if (move[0] == 2 - move[1]) d2 += k;
16+
k *= -1;
17+
}
18+
String result = winnerCheckInArray(rows);
19+
if (!"".equals(result)) return result;
20+
result = winnerCheckInArray(columns);
21+
if (!"".equals(result)) return result;
22+
if (d1 == 3 || d2 == 3) return "A";
23+
if (d1 == -3 || d2 == -3) return "B";
24+
return "";
25+
}
26+
27+
private String winnerCheckInArray(int[] array) {
28+
for (int element : array) {
29+
if (element == 3) return "A";
30+
if (element == -3) return "B";
31+
}
32+
return "";
33+
}
34+
}

0 commit comments

Comments
 (0)