class Solution {
public:
string tictactoe(vector<vector<int>>& moves) {
}
};
1275. 找出井字棋的获胜者
A 和 B 在一个 3 x 3 的网格上玩井字棋。
井字棋游戏的规则如下:
给你一个数组 moves
,其中每个元素是大小为 2
的另一个数组(元素分别对应网格的行和列),它按照 A 和 B 的行动顺序(先 A 后 B)记录了两人各自的棋子位置。
如果游戏存在获胜者(A 或 B),就返回该游戏的获胜者;如果游戏以平局结束,则返回 "Draw";如果仍会有行动(游戏未结束),则返回 "Pending"。
你可以假设 moves
都 有效(遵循井字棋规则),网格最初是空的,A 将先行动。
示例 1:
输入:moves = [[0,0],[2,0],[1,1],[2,1],[2,2]] 输出:"A" 解释:"A" 获胜,他总是先走。 "X " "X " "X " "X " "X " " " -> " " -> " X " -> " X " -> " X " " " "O " "O " "OO " "OOX"
示例 2:
输入:moves = [[0,0],[1,1],[0,1],[0,2],[1,0],[2,0]] 输出:"B" 解释:"B" 获胜。 "X " "X " "XX " "XXO" "XXO" "XXO" " " -> " O " -> " O " -> " O " -> "XO " -> "XO " " " " " " " " " " " "O "
示例 3:
输入:moves = [[0,0],[1,1],[2,0],[1,0],[1,2],[2,1],[0,1],[0,2],[2,2]] 输出:"Draw" 输出:由于没有办法再行动,游戏以平局结束。 "XXO" "OOX" "XOX"
示例 4:
输入:moves = [[0,0],[1,1]] 输出:"Pending" 解释:游戏还没有结束。 "X " " O " " "
提示:
1 <= moves.length <= 9
moves[i].length == 2
0 <= moves[i][j] <= 2
moves
里没有重复的元素。moves
遵循井字棋的规则。原站题解
python3 解法, 执行用时: 28 ms, 内存消耗: 15 MB, 提交时间: 2022-06-15 11:00:42
class Solution: def tictactoe(self, moves: List[List[int]]) -> str: wins = [ [(0, 0), (0, 1), (0, 2)], [(1, 0), (1, 1), (1, 2)], [(2, 0), (2, 1), (2, 2)], [(0, 0), (1, 0), (2, 0)], [(0, 1), (1, 1), (2, 1)], [(0, 2), (1, 2), (2, 2)], [(0, 0), (1, 1), (2, 2)], [(0, 2), (1, 1), (2, 0)], ] def checkwin(S): for win in wins: flag = True for pos in win: if pos not in S: flag = False break if flag: return True return False A, B = set(), set() for i, (x, y) in enumerate(moves): if i % 2 == 0: A.add((x, y)) if checkwin(A): return "A" else: B.add((x, y)) if checkwin(B): return "B" return "Draw" if len(moves) == 9 else "Pending"