Skip to content
Merged
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
11 changes: 8 additions & 3 deletions 8_puzzle.py
Original file line number Diff line number Diff line change
Expand Up @@ -26,15 +26,20 @@ def priority(self) -> int:
return self.moves + self.manhattan()

def manhattan(self) -> int:
"""Calculate Manhattan distance from current to goal state."""
"""Calculate Manhattan distance using actual goal positions."""
distance = 0
# Create a lookup table for goal tile positions
goal_pos = {self.goal[i][j]: (i, j) for i in range(3) for j in range(3)}

for i in range(3):
for j in range(3):
if self.board[i][j] != 0:
x, y = divmod(self.board[i][j] - 1, 3)
value = self.board[i][j]
if value != 0: # skip the empty tile
x, y = goal_pos[value]
distance += abs(x - i) + abs(y - j)
return distance


def is_goal(self) -> bool:
"""Check if current state matches goal."""
return self.board == self.goal
Expand Down