Skip to content

Commit d6115e9

Browse files
Merge pull request #3050 from Madann06/master
Fix incorrect Manhattan distance calculation for custom goal states
2 parents 4099cff + 9c5f9f6 commit d6115e9

File tree

1 file changed

+8
-3
lines changed

1 file changed

+8
-3
lines changed

8_puzzle.py

Lines changed: 8 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -26,15 +26,20 @@ def priority(self) -> int:
2626
return self.moves + self.manhattan()
2727

2828
def manhattan(self) -> int:
29-
"""Calculate Manhattan distance from current to goal state."""
29+
"""Calculate Manhattan distance using actual goal positions."""
3030
distance = 0
31+
# Create a lookup table for goal tile positions
32+
goal_pos = {self.goal[i][j]: (i, j) for i in range(3) for j in range(3)}
33+
3134
for i in range(3):
3235
for j in range(3):
33-
if self.board[i][j] != 0:
34-
x, y = divmod(self.board[i][j] - 1, 3)
36+
value = self.board[i][j]
37+
if value != 0: # skip the empty tile
38+
x, y = goal_pos[value]
3539
distance += abs(x - i) + abs(y - j)
3640
return distance
3741

42+
3843
def is_goal(self) -> bool:
3944
"""Check if current state matches goal."""
4045
return self.board == self.goal

0 commit comments

Comments
 (0)