The objective is to determine if a given Tic-Tac-Toe board state is valid. A valid Tic-Tac-Toe board state requires that:
More specifically:
A winning line consists of three of the same pieces in a row, column, or diagonal.
Input: A single list of strings representing the Tic-Tac-Toe board state. Each string represents a row on the board.
Output: A boolean value indicating whether the given Tic-Tac-Toe board is valid.
Example:
board = ["O ", " ", " "]
# False because the first move should be 'X'
def validTicTacToe(board):
# Counting the number of X's and O's
x_count = sum(row.count('X') for row in board)
o_count = sum(row.count('O') for row in board)
# Checking if the count of X's and O's is valid
if not (x_count == o_count or x_count == o_count + 1):
return False
# Function to check whether a particular player has won
def is_winner(player):
# All possible winning directions
win_states = [
[board[0][0], board[0][1], board[0][2]],
[board[1][0], board[1][1], board[1][2]],
[board[2][0], board[2][1], board[2][2]],
[board[0][0], board[1][0], board[2][0]],
[board[0][1], board[1][1], board[2][1]],
[board[0][2], board[1][2], board[2][2]],
[board[0][0], board[1][1], board[2][2]],
[board[0][2], board[1][1], board[2][0]]
]
return [player, player, player] in win_states
x_wins = is_winner('X')
o_wins = is_winner('O')
# Both players cannot win the game simultaneously
if x_wins and o_wins:
return False
# If X wins, there must be one more X than O
if x_wins and x_count != o_count + 1:
return False
# If O wins, there must be the same number of X and O
if o_wins and x_count != o_count:
return False
return True
# Example usage:
board = ["XOX", "O O", "XOX"]
print(validTicTacToe(board)) # Output: False (both cannot win simultaneously)
This code checks for valid counts of ‘X’ and ‘O’, ensures that only one player can win, and ensures the conditions for a valid Tic-Tac-Toe game state are maintained.
Got blindsided by a question you didn’t expect?
Spend too much time studying?
Or simply don’t have the time to go over all 3000 questions?