题目链接:794. 有效的井字游戏
考虑游戏规则,当一个玩家同时满足两种“三连”时,这两种三连肯定会有共用的棋子。否则该玩家会放下六颗棋子。因此,在满足棋子数约束(X和O的数目相等,或者X比O多一个)的情况下,任意一种棋子的分布都有可能。当X胜利时,X比O多一个,O胜利时,X和O`的数目相等。
from collections import Counter
from typing import List, Set, Tuple
class Solution:
def is_wined(self, state: Set[Tuple[int, int]]) -> bool:
return (((0, 0) in state) and ((1, 1) in state) and ((2, 2) in state)) or \
(((0, 2) in state) and ((1, 1) in state) and ((2, 0) in state)) or \
any(((i, 0) in state) and ((i, 1) in state) and ((i, 2) in state) for i in range(3)) or \
any(((0, j) in state) and ((1, j) in state) and ((2, j) in state) for j in range(3))
def validTicTacToe(self, board: List[str]) -> bool:
c = Counter(''.join(board))
count_x, count_o = c.get('X', 0), c.get('O', 0)
if count_x != count_o and count_x != count_o + 1:
return False
state_x, state_o = set(), set()
for i, row in enumerate(board):
for j, piece in enumerate(row):
if piece == 'X':
state_x.add((i, j))
elif piece == 'O':
state_o.add((i, j))
return not (count_x == count_o and self.is_wined(state_x)) and not (count_x == count_o + 1 and self.is_wined(state_o))