Valid Tic-Tac-Toe State Problem
Description
LeetCode Problem 794.
Given a Tic-Tac-Toe board as a string array board, return true if and only if it is possible to reach this board position during the course of a valid tic-tac-toe game.
The board is a 3 x 3 array that consists of characters ' ', 'X', and 'O'. The ' ' character represents an empty square.
Here are the rules of Tic-Tac-Toe:
- Players take turns placing characters into empty squares ' '.
- The first player always places 'X' characters, while the second player always places 'O' characters.
- 'X' and 'O' characters are always placed into empty squares, never 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.
Example 1:
Input: board = ["O "," "," "]
Output: false
Explanation: The first player always plays "X".
Example 2:
Input: board = ["XOX"," X "," "]
Output: false
Explanation: Players take turns making moves.
Example 3:
Input: board = ["XXX"," ","OOO"]
Output: false
Example 4:
Input: board = ["XOX","O O","XOX"]
Output: true
Constraints:
- board.length == 3
- board[i].length == 3
- board[i][j] is either 'X', 'O', or ' '.
Solution
Approach: Count the Marks and Check the Winners
There is no need to replay games. A board is reachable exactly when it passes three checks on the number of marks and on who has three in a row:
- Turn order.
Xmoves first and the players alternate, so eitheroCount == xCount(it isX's turn) oroCount == xCount - 1(it isO's turn). Anything else is impossible, which rules out Examples 1 and 2. Xwon. The game ended right afterX's winning move, soOnever got to answer:xCountmust beoCount + 1.Owon. The game ended right afterO's move, soxCountmust equaloCount.
If both players have a line, checks 2 and 3 cannot both hold, so the board is rejected (Example 3). A board that passes all three can always be reached by playing the marks in a suitable order.
To find a winner, check the three rows, the three columns and the two diagonals for three copies of the player's mark.
The detail people get wrong is the case where X has two lines at once, such as ["XXX","XOO","XOO"]. It looks like a game that went on after a win, but it is valid: X's fifth mark, in the corner, completes the row and the column in the same move. So only the counts are compared, never the number of lines.
Complexity: O(1) time and O(1) space, since the board is always 3 x 3.
class Solution:
def validTicTacToe(self, board: List[str]) -> bool:
x_count = sum(row.count("X") for row in board)
o_count = sum(row.count("O") for row in board)
# X moves first and the players alternate.
if o_count != x_count and o_count != x_count - 1:
return False
# The game stops right after the winning move.
if self.wins(board, "X") and x_count != o_count + 1:
return False
if self.wins(board, "O") and x_count != o_count:
return False
return True
def wins(self, board: List[str], player: str) -> bool:
for i in range(3):
if all(board[i][j] == player for j in range(3)): # row i
return True
if all(board[j][i] == player for j in range(3)): # column i
return True
if all(board[i][i] == player for i in range(3)): # main diagonal
return True
return all(board[i][2 - i] == player for i in range(3)) # anti-diagonal