原题
A Tic-Tac-Toe board is given as a string array board. Return True if and only if it is possible to reach this board position during the course of a valid tic-tac-toe game.
The board is a 3 x 3 array, and consists of characters " ", “X”, and “O”. The " " character represents an empty square.
Here are the rules of Tic-Tac-Toe:
Players take turns placing characters into empty squares (" ").
The first player always places “X” characters, while the second player always places “O” characters.
“X” and “O” characters are always placed into empty squares, never filled ones.
The game ends when there are 3 of the same (non-empty) character filling any row, column, or diagonal.
The game also ends if all squares are non-empty.
No more moves can be played if the game is over.
Example 1:
Input: board = ["O ", " ", " "]
Output: false
Explanation: The first player always plays “X”.
Example 2:
Input: board = [“XOX”, " X ", " "]
Output: false
Explanation: Players take turns making moves.
Example 3:
Input: board = [“XXX”, " ", “OOO”]
Output: false
Example 4:
Input: board = [“XOX”, “O O”, “XOX”]
Output: true
Note:
board is a length-3 array of strings, where each string board[i] has length 3.
Each board[i][j] is a character in the set {" ", “X”, “O”}.
解法
先检查棋牌上X和O的个数, X要么和O相等, 要么比O多一个, 否则返回False. 然后检查获胜条件: X和O不可同时获胜, 并且如果一方胜利, 另一方不可以继续下棋.
代码
class Solution:
def validTicTacToe(self, board: List[str]) -> bool:
# count X and O
count_x, count_o = 0, 0
for row in board:
count_x += row.count('X')
count_o += row.count('O')
if not(count_x == count_o or count_x - count_o == 1):
return False
# check wining condition
win_x, win_o = False, False
def win(mark):
for row in board:
if row == mark*3:
return True
for c in range(3):
col = [board[r][c] for r in range(3)]
col = ''.join(col)
if col == mark*3:
return True
d1 = [board[i][i] for i in range(3)]
d2 = [board[i][2-i] for i in range(3)]
if d1 == [mark]*3 or d2 == [mark]*3:
return True
return False
if win('X'):
win_x = True
if win('O'):
win_o = True
if win_x and win_o:
return False
if win_x:
if count_o < count_x:
return True
return False
if win_o:
if count_o == count_x:
return True
return False
return True