0% found this document useful (0 votes)
3 views5 pages

AI Lab Experiment-4

The document describes a Python program to solve the 8-puzzle problem using the A-star search algorithm with the Manhattan distance heuristic. It outlines the rules of the puzzle, the methods for solving it, and provides a code implementation along with an example usage. The program aims to find the shortest sequence of moves to arrange the tiles in the correct order from a given start state to the goal state.

Uploaded by

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

AI Lab Experiment-4

The document describes a Python program to solve the 8-puzzle problem using the A-star search algorithm with the Manhattan distance heuristic. It outlines the rules of the puzzle, the methods for solving it, and provides a code implementation along with an example usage. The program aims to find the shortest sequence of moves to arrange the tiles in the correct order from a given start state to the goal state.

Uploaded by

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

4. Write a Program to Implement 8-Puzzle problem using Python.

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.

Rules of the 8-Puzzle Problem:

1. You can only move a tile that is adjascent to the empty space (0).

2. You cannot move tiles diagonally.

3. The goal is to arrange the tiles in increasing order from 1 to 8, with 0 in the bottom-right
corner.

4. Some puzzles may be unsolvable depending on the initial arrangement.

Solving the 8-Puzzle Problem:

To solve the problem, we use search algorithms, such as:

1. Brute Force Methods(blind/uninformed):

o Breadth-First Search (BFS)

o Depth-First Search (DFS)

2. Optimal Algorithms (Heuristic-Based/informed):

o A (A-Star) Search Algorithm

o Greedy Best-First Search

o IDA Search (Iterative Deepening A)**

Most efficient solutions use A search with the Manhattan distance heuristic.

Steps:

1.Compute Manhattan heuristic for each state.

2. Find valid moves by shifting 0.

3. Use A algorithm* to explore the best paths.

4. Stop when the goal state is reached.

5. Print the sequence of moves in matrix form.


Real-Life Applications:

The 8-puzzle problem is a simplified version of many real-world challenges, such as:

● Artificial Intelligence (AI) & Robotics – Pathfinding problems


● Game Development – Tile-based games like Sudoku
● Automated Planning – Logistics & scheduling problems
● Machine Learning – State-space search problems

Example:

Initial (Start) State:

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 heuristic(state, goal):

return sum(abs(b % 3 - g % 3) + abs(b//3 - g//3)

for b, g in ((state.index(i), goal.index(i)) for i in range(1, 9)))

def get_neighbors(state):

neighbors = []

zero_index = state.index(0) # Find the position of the empty tile (0)

row, col = zero_index // 3, zero_index % 3 # Convert index to row and column

moves = [(-1, 0), (1, 0), (0, -1), (0, 1)] # Up, Down, Left, Right
for dr, dc in moves:

new_row, new_col = row + dr, col + dc

if 0 <= new_row < 3 and 0 <= new_col < 3: # Ensure move is within bounds

new_index = new_row * 3 + new_col

new_state = list(state) # Convert tuple to list for swapping

new_state[zero_index], new_state[new_index] = new_state[new_index],


new_state[zero_index] # Swap 0 with adjacent tile

neighbors.append(tuple(new_state)) # Convert back to tuple and store

return neighbors

def solve_puzzle(start, goal):

pq = [(heuristic(start, goal), 0, start, [])] # (priority, moves, state, path)

visited = set() # Keeps track of visited states to avoid loops

while pq:

_, moves, state, path = heapq.heappop(pq) # Get the state with the lowest cost

if state == goal: # If goal is reached, return solution path

return path + [state]

if state in visited:

continue # Skip already visited states

visited.add(state) # Mark state as visited

for neighbor in get_neighbors(state): # Generate valid moves

heapq.heappush(pq, (moves + 1 + heuristic(neighbor, goal), moves + 1, neighbor, path +


[state]))

return None # If no solution found, return None


# Example Usage

start_state = (1, 2, 3, 0, 4, 6, 7, 5, 8)

goal_state = (1, 2, 3, 4, 5, 6, 7, 8, 0)

solution = solve_puzzle(start_state, goal_state)

if solution:

for step in solution:

print(np.array(step).reshape(3, 3)) # Convert tuple into a 3×3 matrix

print()

else:

print("No solution found.")

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]]

You might also like