Programs
Programs
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
def dfs(graph, start, visited=None):
if visited is None:
visited = set()
visited.add(start)
print(start)
dfs(graph, '0')
output:
Program 03: Write a Program to implement Tic-Tac-Toe game using python.
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)]
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)
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!")