Find Winner on a Tic Tac Toe Game LeetCode solution in Java

1
/**
2
* Here is my solution :
3
*
4
* <p>Time Complexity O(M) Space Complaexity O(1)
5
*/
6
class Solution {
7
public String tictactoe(int[][] moves) {
8

9
int[][] rcd = new int[3][3]; // rcd[0] --> rows , rcd[1] --> columns , rcd[2] --> diagonals
10

11
for (int turn = 0; turn < moves.length; turn++) {
12

13
int AorB = -1;
14
if (turn % 2 == 0) {
15
AorB = 1;
16
}
17

18
rcd[0][moves[turn][0]] += AorB;
19
rcd[1][moves[turn][1]] += AorB;
20

21
if (moves[turn][0] == moves[turn][1]) {
22
rcd[2][0] += AorB;
23
} // first diagonal
24
if (moves[turn][0] + moves[turn][1] - 2 == 0) {
25
rcd[2][1] += AorB;
26
} // 2nd diagonal
27

28
if (Math.abs(rcd[0][moves[turn][0]]) == 3
29
|| Math.abs(rcd[1][moves[turn][1]]) == 3
30
|| Math.abs(rcd[2][0]) == 3
31
|| Math.abs(rcd[2][1]) == 3) {
32

33
return AorB == 1 ? "A" : "B";
34
}
35
}
36

37
return moves.length == 9 ? "Draw" : "Pending";
38
}
39
}

0

WPM •0 •0

100%

ACC •0 •0

0s

TIME •0