AI Lab Experiment-4
AI Lab Experiment-4
Description:
The 8-puzzle problem is a classic sliding puzzle that consists of a 3×3 grid with eight numbered tiles
(1-8) and one empty space (0). The goal is to arrange the tiles in the correct order by sliding them
into the empty space.
This program uses the A (A-star) search algorithm* with the Manhattan distance heuristic to find
the shortest sequence of moves from a given start state to the goal state.
1. You can only move a tile that is adjascent to the empty space (0).
3. The goal is to arrange the tiles in increasing order from 1 to 8, with 0 in the bottom-right
corner.
Most efficient solutions use A search with the Manhattan distance heuristic.
Steps:
The 8-puzzle problem is a simplified version of many real-world challenges, such as:
Example:
1 2 3
0 4 6
7 5 8
Goal State:
1 2 3
4 5 6
7 8 0
You can only move tiles up, down, left, or right into the empty space (0), making it a constraint
satisfaction problem.
Code:
import heapq
import numpy as np
def get_neighbors(state):
neighbors = []
moves = [(-1, 0), (1, 0), (0, -1), (0, 1)] # Up, Down, Left, Right
for dr, dc in moves:
if 0 <= new_row < 3 and 0 <= new_col < 3: # Ensure move is within bounds
return neighbors
while pq:
_, moves, state, path = heapq.heappop(pq) # Get the state with the lowest cost
if state in visited:
start_state = (1, 2, 3, 0, 4, 6, 7, 5, 8)
goal_state = (1, 2, 3, 4, 5, 6, 7, 8, 0)
if solution:
print()
else:
output:
[[1 2 3]
[0 4 6]
[7 5 8]]
[[1 2 3]
[4 0 6]
[7 5 8]]
[[1 2 3]
[4 5 6]
[7 0 8]]
[[1 2 3]
[4 5 6]
[7 8 0]]