Design an algorithm to figure out if someone has won a game of tic-tac-toe. Input is a string array of size N x N, including characters " ", "X" and "O", where " " represents a empty grid.
The rules of tic-tac-toe are as follows:
Players place characters into an empty grid(" ") in turn.
The first player always place character "O", and the second one place "X".
Players are only allowed to place characters in empty grid. Replacing a character is not allowed.
If there is any row, column or diagonal filled with N same characters, the game ends. The player who place the last charater wins.
When there is no empty grid, the game ends.
If the game ends, players cannot place any character further.
If there is any winner, return the character that the winner used. If there's a draw, return "Draw". If the game doesn't end and there is no winner, return "Pending".
Example 1:
Input: board = ["O X"," XO","X O"]
Output: "X"
Example 2:
Input: board = ["OOX","XXO","OXO"]
Output: "Draw"
Explanation: no player wins and no empty grid left
Example 3:
Input: board = ["OOX","XXO","OX "]
Output: "Pending"
Explanation: no player wins but there is still a empty grid
Note:
1 <= board.length == board[i].length <= 100
Input follows the rules.
Solutions
Solution 1: Counting
For each cell, if it is X, we can add $1$ to the count; if it is O, we can subtract $1$ from the count. When the absolute value of the count of a row, column, or diagonal equals $n$, it means that the current player has placed $n$ identical characters in that row, column, or diagonal, and the game is over. We can return the corresponding character.
Specifically, we use a one-dimensional array $rows$ and $cols$ of length $n$ to represent the count of each row and column, and use $dg$ and $udg$ to represent the count of the two diagonals. When a player places a character at $(i, j)$, we update the corresponding elements in the arrays $rows$, $cols$, $dg$, and $udg$ based on whether the character is X or O. After each update, we check whether the absolute value of the corresponding element equals $n$. If it does, it means that the current player has placed $n$ identical characters in that row, column, or diagonal, and the game is over. We can return the corresponding character.
Finally, we traverse the entire board. If there is a character , it means that the game is not over yet, and we return Pending. Otherwise, we return Draw.
The time complexity is $O(n^2)$, and the space complexity is $O(n)$, where $n$ is the side length of the board.