[
design
hash table
]
Leetcode 0348. Design Tic-Tac-Toe
Problem statement
https://leetcode.com/problems/design-tic-tac-toe/
Solution
Let us keep board
as well as scores for each row, column and two diagonals. By score I mean we will add $1$ for the first player and $n+1$ for the second. Then if we get score $n$, it means, that first player wins, if we get score $n(n+1)$, it means the second wins and if we have something else, no one wins.
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 player
return 0