思路:
计算正确的可能情况。
第一种:O 走最后一步,X和O的个数相等,X则没有形成三连串, O可能形成0~2条三连串。
第二种:X 走最后一步,X个数比O多1,O则没有形成三连串,X可能形成0~2条三连串。
code:
class Solution:
def validTicTacToe(self, board: List[str]) -> bool:
def judge(board, ch):
cnt = 0
for i in range(3):
if board[i] == ch * 3:
cnt += 1
for j in range(3):
s = ''
for i in range(3):
s += board[i][j]
if s == ch * 3:
cnt += 1
if board[1][1] == ch and board[0][0] == ch and board[2][2] == ch:
cnt += 1
if board[1][1] == ch and board[0][2] == ch and board[2][0] == ch:
cnt += 1
return cnt
x, o = 0, 0
for row in board:
for ch in row:
if ch == 'X':
x += 1
if ch == 'O':
o += 1
if x == o: # O 走最后一步
if judge(board, 'X') == 0 and judge(board, 'O') <= 2:
return True
if x == o + 1: # X 走最后一步
if judge(board, 'O') == 0 and judge(board, 'X') <= 2:
return True
return False