[
design
hash table
]
BinarySearch 0928 Tic Tac Toe
Problem statement
https://binarysearch.com/problems/Tic-Tac-Toe/
Solution
Equal to Leetcode 0348. Design Tic-Tac-Toe.
Complexity
It is O(n^2)
for initialization and just O(1)
to make move.
Code
class TicTacToe:
def __init__(self, n):
self.board = [[0] * n for _ in range(n)]
self.rows = [0]*n
self.cols = [0]*n
self.d1, self.d2 = 0, 0
self.n = n
def move(self, row, col, player):
self.board[row][col] = player
addon = 1 if player == 1 else self.n + 1
self.rows[row] += addon
self.cols[col] += addon
if col == row: self.d1 += addon
if col + row == self.n - 1: self.d2 += addon
if self.n*addon in [self.rows[row], self.cols[col], self.d1, self.d2]:
return 2*int(player) - 1
return 0