Problem : https://leetcode.com/problems/find-winner-on-a-tic-tac-toe-game/
Keep tracking counters of the 3 rows / columns and the 2 diagonals.
Increase counter by 1 if it is player 'A' otherwise decrease counter by 1 for player 'B'.
Player 'A' wins if any counter equals to 3. Player 'B' wins if any counter equals to -3.
class Solution:
def tictactoe(self, moves: List[List[int]]) -> str:
rows = [0] * 3
cols = [0] * 3
diag1 = 0
diag2 = 0
for i, (y, x) in enumerate(moves):
player = 1 if i & 1 == 0 else -1
rows[y] += player
cols[x] += player
if y == x:
diag1 += player
if y == 2 - x:
diag2 += player
if rows[y] == 3 or cols[x] == 3 or diag1 == 3 or diag2 == 3:
return 'A'
if rows[y] == -3 or cols[x] == -3 or diag1 == -3 or diag2 == -3:
return 'B'
return 'Draw' if len(moves) >= 9 else 'Pending'
No comments:
Post a Comment