[LeetCode] Find Winner on a Tic Tac Toe Game

1275. Find Winner on a Tic Tac Toe Game

Tic-tac-toe is played by two players A and B on a 3 x 3 grid. The rules of Tic-Tac-Toe are:

  • Players take turns placing characters into empty squares ' '.
  • The first player A always places 'X' characters, while the second player B always places 'O' characters.
  • 'X' and 'O' characters are always placed into empty squares, never on filled ones.
  • The game ends when there are three of the same (non-empty) character filling any row, column, or diagonal.
  • The game also ends if all squares are non-empty.
  • No more moves can be played if the game is over.

Given a 2D integer array moves where moves[i] = [rowi, coli] indicates that the ith move will be played on grid[rowi][coli]. return the winner of the game if it exists (A or B). In case the game ends in a draw return "Draw". If there are still movements to play return "Pending".

You can assume that moves is valid (i.e., it follows the rules of Tic-Tac-Toe), the grid is initially empty, and A will play first.

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
class Solution {
int dy[8]{-1,-1,-1,0,1,1,1,0}, dx[8]{-1,0,1,1,1,0,-1,-1};
bool fin(vector<vector<int>>& g) {
if(g[0][1] != -1) {
if(g[0][0] == g[0][1] and g[0][1] == g[0][2]) return true;
if(g[0][1] == g[1][1] and g[1][1] == g[2][1]) return true;
}
if(g[1][0] != -1) {
if(g[0][0] == g[1][0] and g[1][0] == g[2][0]) return true;
}
if(g[1][2] != -1) {
if(g[0][2] == g[1][2] and g[1][2] == g[2][2]) return true;
}
if(g[2][1] != -1) {
if(g[2][0] == g[2][1] and g[2][1] == g[2][2]) return true;
}
if(g[1][1] != -1) {
if(g[1][0] == g[1][1] and g[1][1] == g[1][2]) return true;
if(g[0][0] == g[1][1] and g[1][1] == g[2][2]) return true;
if(g[0][2] == g[1][1] and g[1][1] == g[2][0]) return true;
}
return false;
}
public:
string tictactoe(vector<vector<int>>& moves) {
vector<vector<int>> grid(3,vector<int>(3,-1));
bool fl = 0;
for(auto m : moves) {
grid[m[0]][m[1]] = fl;
if(fin(grid)) return fl ? "B" : "A";
fl = !fl;
}
return moves.size() != 9 ? "Pending" : "Draw";
}
};
Author: Song Hayoung
Link: https://songhayoung.github.io/2023/07/30/PS/LeetCode/find-winner-on-a-tic-tac-toe-game/
Copyright Notice: All articles in this blog are licensed under CC BY-NC-SA 4.0 unless stating additionally.