1+ class Solution :
2+ def tictactoe (self , moves : List [List [int ]]) -> str :
3+
4+ # Initialize the board, n = 3 in this problem.
5+ n = 3
6+ board = [[0 ] * n for _ in range (n )]
7+
8+ # Check if any of 4 winning conditions to see if the current player has won.
9+ def checkRow (row , player_id ):
10+ for col in range (n ):
11+ if board [row ][col ] != player_id :
12+ return False
13+ return True
14+
15+ def checkCol (col , player_id ):
16+ for row in range (n ):
17+ if board [row ][col ] != player_id :
18+ return False
19+ return True
20+
21+ def checkDiagonal (player_id ):
22+ for row in range (n ):
23+ if board [row ][row ] != player_id :
24+ return False
25+ return True
26+
27+ def checkAntiDiagonal (player_id ):
28+ for row in range (n ):
29+ if board [row ][n - 1 - row ] != player_id :
30+ return False
31+ return True
32+
33+ # Start with player_1.
34+ player = 1
35+
36+ for move in moves :
37+ # extract
38+ row , col = move
39+ board [row ][col ] = player
40+
41+ # If any of the winning conditions is met, return the current player's id.
42+ if checkRow (row , player ) or checkCol (col , player ) or \
43+ (row == col and checkDiagonal (player )) or \
44+ (row + col == n - 1 and checkAntiDiagonal (player )):
45+ return 'A' if player == 1 else 'B'
46+
47+ # If no one wins so far, change to the other player alternatively.
48+ # That is from 1 to -1, from -1 to 1.
49+ player *= - 1
50+
51+ # If all moves are completed and there is still no result, we shall check if
52+ # the grid is full or not. If so, the game ends with draw, otherwise pending.
53+ return "Draw" if len (moves ) == n * n else "Pending"
0 commit comments