Skip to content

Commit 62df638

Browse files
Merge pull request #2529 from ayushh0406/patch-5
8_puzzle.py
2 parents 716b158 + 8a94fd3 commit 62df638

File tree

2 files changed

+92
-457
lines changed

2 files changed

+92
-457
lines changed

8_puzzle.py

Lines changed: 92 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,92 @@
1+
from queue import PriorityQueue
2+
3+
class PuzzleState:
4+
def __init__(self, board, goal, moves=0, previous=None):
5+
self.board = board
6+
self.goal = goal
7+
self.moves = moves
8+
self.previous = previous
9+
10+
def __lt__(self, other):
11+
return self.priority() < other.priority()
12+
13+
def priority(self):
14+
return self.moves + self.manhattan()
15+
16+
def manhattan(self):
17+
distance = 0
18+
for i in range(3):
19+
for j in range(3):
20+
if self.board[i][j] != 0:
21+
x, y = divmod(self.board[i][j] - 1, 3)
22+
distance += abs(x - i) + abs(y - j)
23+
return distance
24+
25+
def is_goal(self):
26+
return self.board == self.goal
27+
28+
def neighbors(self):
29+
neighbors = []
30+
x, y = next((i, j) for i in range(3) for j in range(3) if self.board[i][j] == 0)
31+
directions = [(-1, 0), (1, 0), (0, -1), (0, 1)]
32+
33+
for dx, dy in directions:
34+
nx, ny = x + dx, y + dy
35+
if 0 <= nx < 3 and 0 <= ny < 3:
36+
new_board = [row[:] for row in self.board]
37+
new_board[x][y], new_board[nx][ny] = new_board[nx][ny], new_board[x][y]
38+
neighbors.append(PuzzleState(new_board, self.goal, self.moves + 1, self))
39+
40+
return neighbors
41+
42+
def solve_puzzle(initial_board, goal_board):
43+
initial_state = PuzzleState(initial_board, goal_board)
44+
frontier = PriorityQueue()
45+
frontier.put(initial_state)
46+
explored = set()
47+
48+
while not frontier.empty():
49+
current_state = frontier.get()
50+
51+
if current_state.is_goal():
52+
return current_state
53+
54+
explored.add(tuple(map(tuple, current_state.board)))
55+
56+
for neighbor in current_state.neighbors():
57+
if tuple(map(tuple, neighbor.board)) not in explored:
58+
frontier.put(neighbor)
59+
60+
return None
61+
62+
def print_solution(solution):
63+
steps = []
64+
while solution:
65+
steps.append(solution.board)
66+
solution = solution.previous
67+
steps.reverse()
68+
69+
for step in steps:
70+
for row in step:
71+
print(' '.join(map(str, row)))
72+
print()
73+
74+
# Example usage
75+
initial_board = [
76+
[1, 2, 3],
77+
[4, 0, 5],
78+
[7, 8, 6]
79+
]
80+
81+
goal_board = [
82+
[1, 2, 3],
83+
[4, 5, 6],
84+
[7, 8, 0]
85+
]
86+
87+
solution = solve_puzzle(initial_board, goal_board)
88+
if solution:
89+
print("Solution found:")
90+
print_solution(solution)
91+
else:
92+
print("No solution found.")

0 commit comments

Comments
 (0)