348. Design Tic-Tac-Toe
Design, Array, Hash Table, Matrix, Simulation, AMateList ·Problem Statement
link: LeetCode.cn LeetCode Assume the following rules are for the tic-tac-toe game on an n x n board between two players:
A move is guaranteed to be valid and is placed on an empty block. Once a winning condition is reached, no more moves are allowed. A player who succeeds in placing n of their marks in a horizontal, vertical, or diagonal row wins the game. Implement the TicTacToe class:
TicTacToe(int n) Initializes the object the size of the board n. int move(int row, int col, int player) Indicates that the player with id player plays at the cell (row, col) of the board. The move is guaranteed to be a valid move, and the two players alternate in making moves. Return 0 if there is no winner after the move, 1 if player 1 is the winner after the move, or 2 if player 2 is the winner after the move.
Example:
Input: ["TicTacToe", "move", "move", "move", "move", "move", "move", "move"][[3], [0, 0, 1], [0, 2, 2], [2, 2, 1], [1, 1, 2], [2, 0, 1], [1, 0, 2], [2, 1, 1]]
Output: [null, 0, 0, 0, 0, 0, 0, 1]
Input: root = [4,2,7,2,3,5,null,2,null,null,null,null,null,1]
Output: 2
Constraints: 2 <= n <= 100 player is 1 or 2. 0 <= row, col < n (row, col) are unique for each different call to move. At most n2 calls will be made to move.
Solution Approach
The solution maintains arrays to track the count of marks in each row, column, and diagonal, updating these counts with each move to quickly determine if a player has won.
Algorithm
- Track Counts: Use arrays to keep track of the number of marks for each row, column, and both diagonals, updating these counts with each move.2
- Update Moves: For each move, increment the counts for the respective row, column, and diagonals based on the player’s mark.
- Check Win Conditions: After updating the counts, check if any row, column, or diagonal has reached the required number of marks (equal to the board size) to determine if there is a winner.
Complexity
time complexity: O(1) space complexity: O(n)
Implement
class TicTacToe:
def __init__(self, n: int):
self.rows = [0] * n
self.cols = [0] * n
self.diagonal = 0
self.anti_diagonal = 0
def move(self, row: int, col: int, player: int) -> int:
current_player = 1 if player == 1 else -1
self.rows[row] += current_player
self.cols[col] += current_player
if row == col:
self.diagonal += current_player
if col == len(self.cols) - row - 1:
self.anti_diagonal += current_player
n = len(self.rows)
if(
abs(self.rows[row]) == n
or abs(self.cols[col]) == n
or abs(self.diagonal) == n
or abs(self.anti_diagonal) == 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)