以为有更方便快捷的解法,结果还是需要列举出全部的情况
class Solution:
def win(self, board: List[str], p: str) -> bool:
# 包含同一行同一列和斜对角的情况
return any(board[i][0] == p and board[i][1] == p and
board[i][2] == p or
board[0][i] == p and board[1][i] == p and
board[2][i] == p for i in range(3)) or \
board[0][0] == p and board[1][1] == p and \
board[2][2] == p or board[2][0] == p and \
board[1][1] == p and board[0][2] == p
def validTicTacToe(self, board: List[str]) -> bool:
# 统计X和O的个数
cnt_x = sum(row.count('X') for row in board)
cnt_o = sum(row.count('O') for row in board)
# O的数量小于等于X
# O赢的情况下O的数量和X的数量是一样多的
# X赢的情况下O的数量总是比X少一个
return not (cnt_o != cnt_x and cnt_o != cnt_x - 1 or
cnt_o != cnt_x and self.win(board, 'O') or
cnt_o != cnt_x - 1 and self.win(board, 'X'))