0% found this document useful (0 votes)
0 views

Programs

The document contains four Python programs: the first implements Breadth First Search (BFS) for graph traversal, the second implements Depth First Search (DFS), the third is a Tic-Tac-Toe game, and the fourth implements the A* algorithm for solving an 8-puzzle game. Each program includes function definitions and example usage. The document provides a comprehensive overview of various algorithms and game implementations in Python.

Uploaded by

mmanojm005
Copyright
© © All Rights Reserved
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
0 views

Programs

The document contains four Python programs: the first implements Breadth First Search (BFS) for graph traversal, the second implements Depth First Search (DFS), the third is a Tic-Tac-Toe game, and the fourth implements the A* algorithm for solving an 8-puzzle game. Each program includes function definitions and example usage. The document provides a comprehensive overview of various algorithms and game implementations in Python.

Uploaded by

mmanojm005
Copyright
© © All Rights Reserved
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
You are on page 1/ 6

Program 01: Write a program to implement Breadth First search using Python.

from collections import deque


def bfs(graph, start):
visited = set() # To keep track of visited nodes
queue = deque([start]) # Initialize queue with the start node
result = [] # To store the BFS traversal order
while queue:
node = queue.popleft() # Dequeue a node
if node not in visited:
visited.add(node) # Mark node as visited
result.append(node) # Store traversal order
queue.extend(graph.get(node, [])) # Enqueue all unvisited neighbors
return result
# Example usage
graph = {
'A': ['B', 'C'],
'B': ['A', 'D', '2'],
'C': ['A', 'F', 'G'],
'D': ['B'],
'2': ['B', 'H'],
'F': ['C'],
'G': ['C'],
'H': ['2']
}
start_node = 'A'
print("BFS Traversal:", bfs(graph, start_node))

Output:
BFS Traversal: ['A', 'B', 'C', 'D', '2', 'F', 'G', 'H']
Program 02: Write a Program to implement Depth First search algorithm using python.

# DFS algorithm in Python

# DFS algorithm
def dfs(graph, start, visited=None):
if visited is None:
visited = set()
visited.add(start)

print(start)

for next in graph[start] - visited:


dfs(graph, next, visited)
return visited

graph = {'0': set(['1', '2']),


'1': set(['0', '3', '4']),
'2': set(['0']),
'3': set(['1']),
'4': set(['2', '3'])}

dfs(graph, '0')
output:
Program 03: Write a Program to implement Tic-Tac-Toe game using python.

# Tic-Tac-Toe Game in Python


# Function to initialize the board
def initialize_board():
return [[' ' for _ in range(3)] for _ in range(3)]
# Function to print the board
def print_board(board):
for row in board:
print('|'.join(row))
print('-' * 5)
# Function to check if a player has won
def check_winner(board, player):
# Check rows and columns
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
# Check diagonals
if all(board[i][i] == player for i in range(3)) or all(board[i][2 - i] == player for i in
range(3)):
return True
return False
# Function to check if the board is full
def is_draw(board):
return all(board[i][j] != ' ' for i in range(3) for j in range(3))
# Function to handle player moves
def make_move(board, player):
while True:
try:
row, col = map(int, input(f"Player {player}, enter row and column (0-2): ").split())
if board[row][col] == ' ':
board[row][col] = player
break
else:
print("Cell already occupied! Choose another one.")
except (ValueError, IndexError):
print("Invalid input! Enter row and column as two numbers between 0 and 2.")
# Main game function
def play_tic_tac_toe():
board = initialize_board()
current_player = 'X'
while True:
print_board(board)
make_move(board, current_player)
if check_winner(board, current_player):
print_board(board)
print(f"Player {current_player} wins!")
break
if is_draw(board):
print_board(board)
print("It's a draw!")
break
# Switch player
current_player = 'O' if current_player == 'X' else 'X'
# Start the game
if __name__ == "__main__":
play_tic_tac_toe()

Output:
Program 04: Write a program to implement 8-puzzle game using python.

import heapq
import numpy as np

def find_zero(board):
x, y = np.where(board == 0)
return x[0], y[0] # Extract first element properly

def get_moves(board):
x, y = find_zero(board)
moves = []
directions = [(0, 1), (1, 0), (0, -1), (-1, 0)]

for dx, dy in directions:


nx, ny = x + dx, y + dy
if 0 <= nx < 3 and 0 <= ny < 3:
new_board = board.copy()
new_board[x, y], new_board[nx, ny] = new_board[nx, ny], new_board[x, y]
moves.append(new_board)

return moves

def heuristic(board):
goal = np.array([[1, 2, 3], [4, 5, 6], [7, 8, 0]])
return int(np.sum(board != goal)) # Ensure heuristic returns an integer

def a_star(initial_board):
pq = [(heuristic(initial_board), 0, tuple(map(tuple, initial_board)), [])]
visited = set()
goal_state = tuple(map(tuple, np.array([[1, 2, 3], [4, 5, 6], [7, 8, 0]])))

while pq:
_, moves, board, path = heapq.heappop(pq)

if board == goal_state:
return path + [board]

visited.add(board)

for move in get_moves(np.array(board)):


move_tuple = tuple(map(tuple, move))
if move_tuple not in visited:
heapq.heappush(pq, (heuristic(move) + moves + 1, moves + 1, move_tuple, path +
[board]))

return None

if __name__ == "__main__":
initial_board = np.array([[1, 2, 3], [4, 0, 6], [7, 5, 8]])
solution = a_star(initial_board)

if solution:
for step, board in enumerate(solution):
print(f"Step {step}:")
print(np.array(board), "\n")
else:
print("No solution found!")

You might also like