Experiment 3
Experiment 3
Aim: Implement Best first search and least cost search for 8-Puzzle
problem
Theory:
Given a 3×3 board with 8 tiles (each numbered from 1 to 8) and one
empty space, the objective is to place the numbers to match the final
configuration using the empty space. We can slide four adjacent tiles
(left, right, above, and below) into the empty space.
Code:
import copy
from heapq import heappush, heappop
n=3
row = [1, 0, -1, 0]
col = [0, -1, 0, 1]
class priorityQueue:
def __init__(self):
self.heap = []
1
def push(self, k):
heappush(self.heap, k)
def pop(self):
return heappop(self.heap)
def empty(self):
return not self.heap
class node:
def __init__(self, parent, mat, empty_tile_pos, cost, level):
self.parent = parent
self.mat = mat
self.empty_tile_pos = empty_tile_pos
self.cost = cost
self.level = level
def printMatrix(mat):
for i in range(n):
for j in range(n):
print("%d " % (mat[i][j]), end=" ")
print()
3
def printPath(root):
if root is None:
return
printPath(root.parent)
printMatrix(root.mat)
print()
5
Output:
6
Aim: Implement the steps of A* Algorithms for 8-Puzzle problem.
Theory:
The A* (A-Star) algorithm is a popular pathfinding and graph traversal
algorithm that is widely used in AI to find the shortest path from a
start state to a goal state. It is particularly useful for solving problems
like the 8-puzzle.
Code:
import heapq
import copy
7
return distance
def get_neighbors(state):
neighbors = []
x, y = next((i, j) for i in range(3) for j in range(3) if state[i][j] == 0)
moves = [(-1, 0), (1, 0), (0, -1), (0, 1)]
for dx, dy in moves:
nx, ny = x + dx, y + dy
if 0 <= nx < 3 and 0 <= ny < 3:
new_state = copy.deepcopy(state)
new_state[x][y], new_state[nx][ny] = new_state[nx][ny],
new_state[x][y]
neighbors.append(new_state)
return neighbors
8
f, g, current, path = heapq.heappop(pq)
if is_goal(current, goal):
return path + [current]
visited.add(tuple(map(tuple, current)))
for neighbor in get_neighbors(current):
if tuple(map(tuple, neighbor)) not in visited:
heapq.heappush(
pq,
(
g + 1 + manhattan_distance(neighbor, goal),
g + 1,
neighbor,
path + [current],
),
)
return None
Output:
Initial State:
Step:1
Final Stage:
10
11