Problem
Design an algorithm to figure out if someone has won in a game of tic-tac-toe.
OR
Tic-tac-toe is played by two players A and B on a 3 x 3 grid. The rules of Tic-Tac-Toe are:
- Players take turns placing characters into empty squares
' '. - The first player
Aalways places'X'characters, while the second playerBalways places'O'characters. 'X'and'O'characters are always placed into empty squares, never on filled ones.- The game ends when there are three of the same (non-empty) character filling any row, column, or diagonal.
- The game also ends if all squares are non-empty.
- No more moves can be played if the game is over.
Given a 2D integer array moves where moves[i] = [rowi, coli] indicates that the ith move will be played on grid[rowi][coli]. return the winner of the game if it exists (A or B). In case the game ends in a draw return "Draw". If there are still movements to play return "Pending".
You can assume that moves is valid (i.e., it follows the rules of Tic-Tac-Toe), the grid is initially empty, and A will play first.
Examples
Example 1:
$$ grid = \begin{bmatrix} \colorbox{lightgreen} X & . & . \\ . & \colorbox{lightgreen} X & . \\ \ O & O & \colorbox{lightgreen} X \end{bmatrix} $$
| |
Example 2:
$$ grid = \begin{bmatrix} X & X & \colorbox{lightgreen} O \\ X & \colorbox{lightgreen} O & . \\ \colorbox{lightgreen} O & . & . \end{bmatrix} $$
| |
Example 3:
$$ grid = \begin{bmatrix} X & X & O \\ O & O & X \\ X & O & X \end{bmatrix} $$
| |
Solution
Method 1 - Run the simulation
Here are the key points:
- Initialization and Moves: Each move is valid and alternates between player A and player B.
- Winning Condition: The game checks if any row, column, or diagonal has the same character (‘X’ or ‘O’) repeated three times.
- End Conditions:
- Win: One player wins if they have three of their marks in a row, column, or diagonal.
- Draw: The game ends in a draw if all cells are filled without a winner.
- Pending: The game is pending if there are still empty cells and no winner.
Here are the steps:
- Set Up the Board: A 3x3 grid initialized to empty.
- Simulate Moves: Apply each move in the given order.
- Check for Winner:
- Check rows, columns, and both diagonals for a win condition after each move.
- Determine Result:
- If a win is detected, return the respective player.
- If all cells are filled, return “Draw”.
- Otherwise, return “Pending”.
Code
| |
| |
Complexity
- ⏰ Time complexity:
O(m), wheremis the number of moves since each move is processed once. Checking for a win condition is constant timeO(1). - 🧺 Space complexity:
O(1)