The naive approach to this problem is to check, after every move, whether the current player has won the game. Either player can win the game if the following conditions are met:
We mark the cell identified by the given row and column indexes with the current player’s marker. Then, we check the following conditions to determine whether the current player wins:
After every move, we iterated up to four times over cells to check for each condition, row, column, diagonal (top-left to bottom-right corner), and anti-diagonal (top-right to bottom-left corner). Therefore, the time complexity is . The space complexity of this naive approach is , because we are using a board of size .
Let’s see if we can use the mark-counting technique to reduce the time and space complexity of our solution.
The following are the three kinds of win scenarios in tic-tac-toe:
A player can win by marking all the cells in a row or a column, or along the diagonal, or, along the anti-diagonal. To identify whether either of the two players wins or if it’s a tie between the two players, we can efficiently count the marks made on the tic-tac-toe board.
Note: In the following section, we will gradually build the solution. Alternatively, you can skip straight to just the code.
The naive approach to this problem is to check, after every move, whether the current player has won the game. Either player can win the game if the following conditions are met:
We mark the cell identified by the given row and column indexes with the current player’s marker. Then, we check the following conditions to determine whether the current player wins:
After every move, we iterated up to four times over cells to check for each condition, row, column, diagonal (top-left to bottom-right corner), and anti-diagonal (top-right to bottom-left corner). Therefore, the time complexity is . The space complexity of this naive approach is , because we are using a board of size .
Let’s see if we can use the mark-counting technique to reduce the time and space complexity of our solution.
The following are the three kinds of win scenarios in tic-tac-toe:
A player can win by marking all the cells in a row or a column, or along the diagonal, or, along the anti-diagonal. To identify whether either of the two players wins or if it’s a tie between the two players, we can efficiently count the marks made on the tic-tac-toe board.
Note: In the following section, we will gradually build the solution. Alternatively, you can skip straight to just the code.