Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Add Python Program to Solve 8 Puzzle Problem Using BFS #467

Open
wants to merge 3 commits into
base: master
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
77 changes: 77 additions & 0 deletions 8puzzleAstar.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,77 @@
import copy
import heapq

class Puzzle:

def __init__(self, initial_state):
self.goal_state = [[1, 2, 3], [4, 5, 6], [7, 8, 0]]
self.initial_state = initial_state
self.open_list = []
self.closed_list = []

def get_heuristic(self, state):
heuristic = 0
for i in range(3):
for j in range(3):
if state[i][j] != 0:
x_goal, y_goal = divmod(state[i][j] - 1, 3)
heuristic += abs(i - x_goal) + abs(j - y_goal)
return heuristic

def get_blank_position(self, state):
for i in range(3):
for j in range(3):
if state[i][j] == 0:
return (i, j)

def get_successors(self, state):
successors = []
i_blank, j_blank = self.get_blank_position(state)
for x, y in [(0, 1), (1, 0), (0, -1), (-1, 0)]:
if 0 <= i_blank + x < 3 and 0 <= j_blank + y < 3:
new_state = copy.deepcopy(state)
new_state[i_blank][j_blank], new_state[i_blank + x][j_blank + y] = new_state[i_blank + x][j_blank + y], new_state[i_blank][j_blank]
successors.append(new_state)
return successors

def solve(self):
start_node = (self.get_heuristic(self.initial_state), self.initial_state, 0, None)
heapq.heappush(self.open_list, start_node)

while self.open_list:
current_node = heapq.heappop(self.open_list)
current_cost = current_node[2]
current_state = current_node[1]

if current_state == self.goal_state:
path = []
while current_node:
path.append(current_node[1])
current_node = current_node[3]
return reversed(path)

self.closed_list.append(current_state)
successors = self.get_successors(current_state)
for successor in successors:
if successor not in self.closed_list:
g_cost = current_cost + 1
h_cost = self.get_heuristic(successor)
f_cost = g_cost + h_cost
new_node = (f_cost, successor, g_cost, current_node)
heapq.heappush(self.open_list, new_node)

return None

# Run the Solver
initial_state = [[1,2, 3], [4,5,6], [0,7,8]]
solver = Puzzle(initial_state)
solution = solver.solve()

if solution:
for idx, state in enumerate(solution):
print(f"Move {idx + 1}:")
for row in state:
print(row)
print()
else:
print("No solution found.")
75 changes: 75 additions & 0 deletions Python/8puzzleBSF.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,75 @@
from collections import deque

def is_goal(state):
return state == [[1, 2, 3], [4, 5, 6], [7, 8, 0]]

def find_moves(state):
moves = []
zero_row, zero_col = find_zero(state)
if zero_row > 0:
moves.append("up")
if zero_row < 2:
moves.append("down")
if zero_col > 0:
moves.append("left")
if zero_col < 2:
moves.append("right")
return moves

def find_zero(state):
for i in range(3):
for j in range(3):
if state[i][j] == 0:
return i, j

def perform_move(state, move):
new_state = [row[:] for row in state]
zero_row, zero_col = find_zero(state)
if move == "up":
new_row, new_col = zero_row - 1, zero_col
elif move == "down":
new_row, new_col = zero_row + 1, zero_col
elif move == "left":
new_row, new_col = zero_row, zero_col - 1
elif move == "right":
new_row, new_col = zero_row, zero_col + 1
new_state[zero_row][zero_col], new_state[new_row][new_col] = new_state[new_row][new_col], new_state[zero_row][zero_col]
return new_state

def solve_puzzle(initial_state):
if is_goal(initial_state):
return [initial_state]

visited = set()
queue = deque([(initial_state, [])])

while queue:
state, path = queue.popleft()
visited.add(tuple(map(tuple, state)))

for move in find_moves(state):
new_state = perform_move(state, move)
if tuple(map(tuple, new_state)) not in visited:
new_path = path + [new_state]
if is_goal(new_state):
return new_path
queue.append((new_state, new_path))

return None

# Example usage:
initial_state = [
[1, 2, 3],
[4, 5, 0],
[7, 8, 6]
]

solution = solve_puzzle(initial_state)
if solution:
print("Solution found in", len(solution)-1, "moves:")
for i, state in enumerate(solution):
print("\nMove", i)
for row in state:
print(row)
else:
print("No solution found.")