Design Tic-Tac-Toe - Problem
Design a Tic-Tac-Toe game that is played between two players on an n × n board. You may assume the following rules:
- 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 with the size of the boardn.int move(int row, int col, int player)Indicates that the player with idplayerplays 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. Return0if there is no winner after the move,1if player 1 is the winner after the move, or2if player 2 is the winner after the move.
Input & Output
Example 1 — Player 1 Wins on 3x3 Board
$
Input:
n = 3, moves: [[0,0,1], [0,2,2], [2,2,1], [1,1,2], [2,0,1], [1,0,2], [1,2,1]]
›
Output:
[null,0,0,0,0,0,0,1]
💡 Note:
Player 1 places marks at (0,0), (2,2), (2,0), (1,2). The last move (1,2) completes the anti-diagonal [0,0]→[1,1]→[2,2], so Player 1 wins.
Example 2 — Row Win on 2x2 Board
$
Input:
n = 2, moves: [[0,0,1], [1,1,2], [0,1,1]]
›
Output:
[null,0,0,1]
💡 Note:
Player 1 fills the entire top row: (0,0) and (0,1). Two marks in a row on a 2x2 board means Player 1 wins.
Example 3 — Column Win
$
Input:
n = 3, moves: [[0,0,1], [1,1,2], [1,0,1], [2,2,2], [2,0,1]]
›
Output:
[null,0,0,0,0,1]
💡 Note:
Player 1 places marks at (0,0), (1,0), (2,0) - filling the entire first column and winning.
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
Visualization
Tap to expand
Understanding the Visualization
1
Input
Board size n and sequence of player moves (row, col, player)
2
Process
Track sums for each row, column, and diagonal using counters
3
Output
Return winner (1 or 2) or 0 if game continues
Key Takeaway
🎯 Key Insight: Use mathematical sums instead of board scanning for instant winner detection
💡
Explanation
AI Ready
💡 Suggestion
Tab
to accept
Esc
to dismiss
// Output will appear here after running code