题目描述:
题解:
1.利用state 一个3*3的数组记录输入board的状态,如果board对应位置为X则将state对应位置设为1,如果是O则将state对应位置设为0,利用xnum onum记录board中X和O数量。
2.如果onum>xnum 或xnum onum之差大于1,则返回False(因为两个玩家总是交替下棋,并且玩家1先下)
3.分别计算state每行,每列,两个对角线位置的值之和,如果和为3,flag1+1,如果为0,flag2+1,flag1 2分别对应x玩家和o玩家获胜的情况。
4.如果x获胜,flag1>flag2,则x的数量应该比o多1.
5.如果o获胜,flag2>flag2,则o的数量应该和x相等。
class Solution: def validTicTacToe(self, board: List[str]) -> bool: state = [[100 for i in range(3)] for j in range(3)] xnum = 0 onum = 0 for i in range(3): line = board[i] linestate = [] for s in line: if s == 'X': xnum = xnum + 1 linestate.append(1) if s == 'O': onum = onum + 1 linestate.append(0) if s == ' ': linestate.append(100) state[i] = linestate print(state) if onum > xnum: return False if abs(onum - xnum) > 1: return False flag1 = 0 flag2 = 0 for i in range(3): diagonal1 = 0 diagonal2 = 0 if sum(state[i]) == 3: flag1 = flag1 + 1 if sum(state[i]) == 0: print("here") flag2 = flag2 + 1 diagonal1 = state[0][0] + state[1][1] + state[2][2] diagonal2 = state[0][2] + state[1][1] + state[2][0] for j in range(3): if sum(s[j] for s in state) == 3: flag1 = flag1 + 1 if sum(s[j] for s in state) == 0: print("here") flag2 = flag2 + 1 if diagonal1 == 3 or diagonal2 == 3: print("here") flag1 = flag1 + 1 if diagonal1 == 0 or diagonal2 == 0: print("here") flag2 = flag2 + 1 print(flag1) print(flag2) if flag2 == flag1 and flag1 != 0: return False if flag1 > flag2: if xnum - onum == 1: return True else: return False if flag2 > flag1: if onum >= xnum: return True else: return False return True