0% found this document useful (0 votes)
66 views2 pages

Implementation of BFS For Tic-Tac-Toe Problem

notes

Uploaded by

rayalbeast1000
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
66 views2 pages

Implementation of BFS For Tic-Tac-Toe Problem

notes

Uploaded by

rayalbeast1000
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 2

In [1]: from collections import deque

def is_winner(board, player):


# Define winning combinations
win_combinations = [
[0,1,2], [3,4,5], [6,7,8], # rows
[0,3,6], [1,4,7], [2,5,8], # columns
[0,4,8], [2,4,6] # diagonals
]
for combo in win_combinations:
if all(board[i] == player for i in combo):
return True
return False

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)

# Check if the previous move caused a win


if path:
last_move = path[-1][0]
last_player = path[-1][1]
if is_winner(state, last_player):
if last_player == target_player:
solution_path = [s for s, p in path]
solution_path.append(state)
return solution_path
else:
continue

# Generate all possible moves


for i in range(9):
if state[i] == '.':
new_board = state[:i] + current_player + state[i+1:]
new_path = path + [ (new_board, current_player) ]
next_player = 'O' if current_player == 'X' else 'X'
queue.append((new_board, new_path, next_player))

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}.")

Winning sequence for X:


X . .
. . .
. . .

X O .
. . .
. . .

X O .
X . .
. . .

X O O
X . .
. . .

X O O
X . .
X . .

X O O
X . .
X . .

In [ ]:

This notebook was converted to PDF with convert.ploomber.io

You might also like