Valid Tic-Tac-Toe State

We can create a function to validate a Tic-Tac-Toe board by observing some constraints:

  1. The number of X’s must be equal to or one more than the number of O’s.
  2. If there are three X’s in a row, then the number of X’s must be one more than the number of O’s.
  3. If there are three O’s in a row, then the number of X’s must be equal to the number of O’s.
  4. There can’t be three X’s and three O’s in a row at the same time.

Here’s a code that implements these constraints:

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
class Solution:
    def validTicTacToe(self, board: List[str]) -> bool:
        # Counting the number of 'X' and 'O'
        xCount = oCount = 0
        for row in board:
            for cell in row:
                if cell == 'X':
                    xCount += 1
                elif cell == 'O':
                    oCount += 1

        # Function to check if a player has won
        def win(player: str) -> bool:
            # Check rows, columns, and diagonals
            for i in range(3):
                if all(board[i][j] == player for j in range(3)) or \
                   all(board[j][i] == player for j in range(3)):
                    return True
            return board[0][0] == board[1][1] == board[2][2] == player or \
                   board[0][2] == board[1][1] == board[2][0] == player

        # Validate the board
        xWin = win('X')
        oWin = win('O')

        if (xWin and xCount != oCount + 1) or \
           (oWin and xCount != oCount) or \
           (xCount < oCount or xCount > oCount + 1) or \
           (xWin and oWin):
            return False
        return True

This code checks for the constraints described above, returning True if the board is valid and False otherwise. It counts the occurrences of X and O, checks for winning conditions, and then validates the board based on the constraints of a valid Tic-Tac-Toe game.