Implementation of BFS For Tic-Tac-Toe Problem
Implementation of BFS For Tic-Tac-Toe Problem
def bfs_tic_tac_toe(target_player='X'):
"""
Perform BFS to find a winning sequence for target_player in Tic-Tac-Toe.
Parameters:
target_player (str): 'X' or 'O'
Returns:
list: Sequence of board states leading to the win
"""
initial_state = '.' * 9
queue = deque([(initial_state, [], 'X')]) # state, path, current_player
visited = set()
while queue:
state, path, current_player = queue.popleft()
if state in visited:
continue
visited.add(state)
return None
def print_board(state):
for i in range(0, 9, 3):
print(state[i] + ' ' + state[i+1] + ' ' + state[i+2])
print()
if __name__ == "__main__":
target_player = 'X'
solution = bfs_tic_tac_toe(target_player)
if solution:
print(f"Winning sequence for {target_player}:")
for step in solution:
print_board(step)
else:
print(f"No winning sequence found for {target_player}.")
X O .
. . .
. . .
X O .
X . .
. . .
X O O
X . .
. . .
X O O
X . .
X . .
X O O
X . .
X . .
In [ ]: