题目地址:
https://leetcode.com/problems/find-winner-on-a-tic-tac-toe-game/
玩Tic Tac Toe游戏,在一个
3
×
3
3\times 3
3×3方格上,先手是
A
A
A,走'X'
,后手是
B
B
B,走'O'
,给定他们每次走的位置,题目保证每次走的时候都是合法的。问胜者是谁,返回胜者名字。如果游戏还可以继续进行则输出“Pending”,否则输出“Draw”。
代码如下:
class Solution {
public:
string tictactoe(vector<vector<int>>& moves) {
char a[3][3] = {0};
auto f = [&](int x, int y, char ch) {
a[x][y] = ch;
string res = ch == 'X' ? "A" : "B";
for (int i = 0; i < 3; i++) {
if (a[i][0] == ch && a[i][1] == ch && a[i][2] == ch) return res;
if (a[0][i] == ch && a[1][i] == ch && a[2][i] == ch) return res;
if (a[0][0] == ch && a[1][1] == ch && a[2][2] == ch) return res;
if (a[0][2] == ch && a[1][1] == ch && a[2][0] == ch) return res;
}
return string();
};
bool b = true;
for (auto& move : moves) {
int x = move[0], y = move[1];
auto res = f(x, y, b ? 'X' : 'O');
if (res.size()) return res;
b = !b;
}
return moves.size() < 9 ? "Pending" : "Draw";
}
};
时空复杂度 O ( 1 ) O(1) O(1)。