348. Design Tic-Tac-Toe
All prompts are owned by LeetCode. To view the prompt, click the title link above.
First completed : July 05, 2024
Last updated : July 05, 2024
Related Topics : Array, Hash Table, Design, Matrix, Simulation
Acceptance Rate : 58.44 %
class TicTacToe:
def __init__(self, n: int):
self.board = [[0] * n for _ in range(n)]
self.n = n
def move(self, row: int, col: int, player: int) -> int:
self.board[row][col] = player
# O(2n)
# Horizontal and vertical wins
if not any(self.board[x][col] != player for x in range(self.n)) \
or not any(self.board[row][x] != player for x in range(self.n)) :
return player
# O(n)
# Diagonal win: top left --> bottom right \\\\
if row == col and not any(self.board[x][x] != player for x in range(self.n)) :
return player
# O(n)
# Diagonal win: bottom left --> top right ////
if row == self.n - col - 1 and not any(self.board[x][self.n - x - 1] != player for x in range(self.n)) :
return player
return 0
# Your TicTacToe object will be instantiated and called as such:
# obj = TicTacToe(n)
# param_1 = obj.move(row,col,player)
class TicTacToe:
def __init__(self, n: int):
self.boardCols = [0] * n
self.boardRows = [0] * n
self.diagonals = [0] * 2
self.n = n
def move(self, row: int, col: int, player: int) -> int:
direction = 1 if (player == 2) else -1
self.boardCols[row] += direction
self.boardRows[col] += direction
if abs(self.boardCols[row]) == self.n \
or abs(self.boardRows[col]) == self.n :
return player
if row == col :
self.diagonals[0] += direction
if abs(self.diagonals[0]) == self.n :
return player
if row == self.n - col - 1 :
self.diagonals[1] += direction
if abs(self.diagonals[1]) == self.n :
return player
return 0
# Your TicTacToe object will be instantiated and called as such:
# obj = TicTacToe(n)
# param_1 = obj.move(row,col,player)