/348. Tic-Tac-Toe Game Winner Detection

348. Tic-Tac-Toe Game Winner Detection

Medium
Arrays58.8% acceptance

Implement a class TicTacToeBoard that supports the following operations for an n x n board:

- Initialization with board size n.

- move(row, col, player): Player 1 or Player 2 makes a move at position (row, col). Return 0 if no one wins, or the player number if that player wins after this move.

A player wins if they fill an entire row, column, or diagonal with their marks.

Example 1

Input: board = TicTacToeBoard(3) output1 = board.move(0, 0, 1) output2 = board.move(1, 1, 2) output3 = board.move(0, 1, 1) output4 = board.move(2, 2, 2) output5 = board.move(0, 2, 1)

Output: output1 = 0 output2 = 0 output3 = 0 output4 = 0 output5 = 1

Explanation: Player 1 wins by filling the first row.

Example 2

Input: board = TicTacToeBoard(4) output1 = board.move(0, 0, 2) output2 = board.move(1, 1, 2) output3 = board.move(2, 2, 2) output4 = board.move(3, 3, 2)

Output: output1 = 0 output2 = 0 output3 = 0 output4 = 2

Explanation: Player 2 wins by filling the main diagonal.

Constraints

  • 1 <= board_size <= 1000
  • 0 <= row < board_size
  • 0 <= col < board_size
  • player in {1, 2}
  • Moves are guaranteed to be valid and not repeated
Python (current runtime)

Case 1

Input: board = TicTacToeBoard(3) res1 = board.move(2, 0, 2) res2 = board.move(1, 1, 1) res3 = board.move(2, 1, 2) res4 = board.move(1, 0, 1) res5 = board.move(2, 2, 2)

Expected: res1 = 0 res2 = 0 res3 = 0 res4 = 0 res5 = 2

Case 2

Input: board = TicTacToeBoard(2) res1 = board.move(0, 0, 1) res2 = board.move(1, 1, 2) res3 = board.move(0, 1, 1)

Expected: res1 = 0 res2 = 0 res3 = 1