Skip to content

Commit 83f1a02

Browse files
authored
Create 20_tic_tac_toe_winner.cpp
1 parent b82cfb4 commit 83f1a02

File tree

1 file changed

+67
-0
lines changed

1 file changed

+67
-0
lines changed
Lines changed: 67 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,67 @@
1+
class Solution {
2+
private:
3+
4+
// Initialize the board, n = 3 in this problem.
5+
int n = 3;
6+
vector<vector<int>> board;
7+
8+
public:
9+
string tictactoe(vector<vector<int>>& moves) {
10+
board.assign(n, vector<int>(n, 0));
11+
int player = 1;
12+
13+
// For each move
14+
for (vector<int> move : moves) {
15+
int row = move[0];
16+
int col = move[1];
17+
18+
// Mark the current move with the current playrer's id.
19+
board[row][col] = player;
20+
21+
// If any of the winning conditions is met, return the current player's id.
22+
if (checkRow(row, player) || checkCol(col, player) ||
23+
(row == col && checkDiagonal(player)) ||
24+
(row + col == n - 1 && checkAntiDiagonal(player))) {
25+
return player == 1 ? "A" : "B";
26+
return player == 1 ? "A" : "B";
27+
}
28+
29+
// If no one wins so far, change to the other player alternatively.
30+
// That is from 1 to -1, from -1 to 1.
31+
player *= -1;
32+
}
33+
34+
// If all moves are completed and there is still no result, we shall check if
35+
// the grid is full or not. If so, the game ends with draw, otherwise pending.
36+
return moves.size() == 3 * 3 ? "Draw" : "Pending";
37+
}
38+
39+
// Check if any of 4 winning conditions to see if the current player has won.
40+
bool checkRow(int row, int player) {
41+
for (int col = 0; col < n; ++col) {
42+
if (board[row][col] != player) return false;
43+
}
44+
return true;
45+
}
46+
47+
bool checkCol(int col, int player) {
48+
for (int row = 0; row < n; ++row) {
49+
if (board[row][col] != player) return false;
50+
}
51+
return true;
52+
}
53+
54+
bool checkDiagonal(int player) {
55+
for (int row = 0; row < n; ++row) {
56+
if (board[row][row] != player) return false;
57+
}
58+
return true;
59+
}
60+
61+
bool checkAntiDiagonal(int player) {
62+
for (int row = 0; row < n; ++row) {
63+
if (board[row][n - 1 - row] != player) return false;
64+
}
65+
return true;
66+
}
67+
};

0 commit comments

Comments
 (0)