Skip to content

Commit 1e45f1d

Browse files
authored
Create find-winner-on-a-tic-tac-toe-game.cpp
1 parent 856b756 commit 1e45f1d

File tree

1 file changed

+25
-0
lines changed

1 file changed

+25
-0
lines changed
Lines changed: 25 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,25 @@
1+
// Time: O(1)
2+
// Space: O(1)
3+
4+
class Solution {
5+
public:
6+
string tictactoe(vector<vector<int>>& moves) {
7+
vector<vector<int>> row(2, vector<int>(3));
8+
vector<vector<int>> col(2, vector<int>(3));
9+
vector<int> diag(2), anti_diag(2);
10+
int p = 0;
11+
for (const auto& move : moves) {
12+
int r = move[0], c = move[1];
13+
++row[p][r];
14+
++col[p][c];
15+
diag[p] += (r == c);
16+
anti_diag[p] += (r + c == 2);
17+
vector<int> tmp = {row[p][r], col[p][c], diag[p], anti_diag[p]};
18+
if (find(tmp.cbegin(), tmp.cend(), 3) != tmp.cend()) {
19+
return string(1, "AB"[p]);
20+
}
21+
p ^= 1;
22+
}
23+
return moves.size() == 9 ? "Draw" : "Pending";
24+
}
25+
};

0 commit comments

Comments
 (0)