Skip to content

1275. Find Winner on a Tic Tac Toe Game 👍

  • Time:
  • Space:
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
class Solution {
 public:
  string tictactoe(vector<vector<int>>& moves) {
    vector<vector<int>> row(2, vector<int>(3));
    vector<vector<int>> col(2, vector<int>(3));
    vector<int> diag1(2);
    vector<int> diag2(2);

    for (int i = 0; i < moves.size(); ++i) {
      const int r = moves[i][0];
      const int c = moves[i][1];
      const int j = i & 1;
      if (++row[j][r] == 3 || ++col[j][c] == 3 || r == c && ++diag1[j] == 3 ||
          r + c == 2 && ++diag2[j] == 3)
        return j == 0 ? "A" : "B";
    }

    return moves.size() == 9 ? "Draw" : "Pending";
  }
};
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
class Solution {
  public String tictactoe(int[][] moves) {
    int[][] row = new int[2][3];
    int[][] col = new int[2][3];
    int[] diag1 = new int[2];
    int[] diag2 = new int[2];

    for (int i = 0; i < moves.length; ++i) {
      final int r = moves[i][0];
      final int c = moves[i][1];
      final int j = i & 1;
      if (++row[j][r] == 3 || ++col[j][c] == 3 || r == c && ++diag1[j] == 3 ||
          r + c == 2 && ++diag2[j] == 3)
        return j == 0 ? "A" : "B";
    }

    return moves.length == 9 ? "Draw" : "Pending";
  }
}
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
class Solution:
  def tictactoe(self, moves: list[list[int]]) -> str:
    row = [[0] * 3 for _ in range(2)]
    col = [[0] * 3 for _ in range(2)]
    diag1 = [0] * 2
    diag2 = [0] * 2
    i = 0

    for r, c in moves:
      row[i][r] += 1
      col[i][c] += 1
      diag1[i] += r == c
      diag2[i] += r + c == 2
      if 3 in (row[i][r], col[i][c], diag1[i], diag2[i]):
        return 'A' if i == 0 else 'B'
      i ^= 1

    return 'Draw' if len(moves) == 9 else 'Pending'