Leetcode 810 Solution
This article provides solution to leetcode question 810 (valid-tic-tac-toe-state)
Access this page by simply typing in "lcs 810" in your browser address bar if you have bunnylol configured.
Leetcode Question Link
https://leetcode.com/problems/valid-tic-tac-toe-state
Solution
class Solution:
def getWins(self, ch, board):
wins = 0
for i in range(3):
if board[i][0] == ch and board[i][1] == ch and board[i][2] == ch:
wins += 1
for j in range(3):
if board[0][j] == ch and board[1][j] == ch and board[2][j] == ch:
wins += 1
if board[0][0] == ch and board[1][1] == ch and board[2][2] == ch:
wins += 1
if board[2][0] == ch and board[1][1] == ch and board[0][2] == ch:
wins += 1
return wins
def isValid(self, ch, board):
valid = False
for i in range(3):
for j in range(3):
old_str = board[i]
board[i] = board[i][:j - 1] + ' ' + board[i][j:]
if self.getWins(ch, board) == 0:
valid = True
board[i] = old_str
return valid
def validTicTacToe(self, board: List[str]) -> bool:
cnt1 = 0
cnt2 = 0
for i in range(3):
for j in range(3):
if board[i][j] == 'X':
cnt1 += 1
elif board[i][j] == 'O':
cnt2 += 1
wins1 = self.getWins('X', board)
wins2 = self.getWins('O', board)
if wins1 > 1:
return self.isValid('X', board) and cnt1 == cnt2 + 1 and wins2 == 0
elif wins1 == 1:
return wins2 == 0 and cnt1 == cnt2 + 1
else:
if wins2 == 0 and (cnt1 == cnt2 or cnt1 == cnt2 + 1):
return True
elif wins2 == 1 and cnt1 == cnt2:
return True
else:
return self.isValid('O', board) and cnt1 == cnt2