MCPcopy
hub / github.com/geekcomputers/Python / solve_puzzle

Function solve_puzzle

8_puzzle.py:62–84  ·  view source on GitHub ↗

Solve 8-puzzle using A* algorithm. >>> solve_puzzle([[1,2,3],[4,0,5],[7,8,6]], [[1,2,3],[4,5,6],[7,8,0]]) is not None True

(
    initial_board: List[List[int]], goal_board: List[List[int]]
)

Source from the content-addressed store, hash-verified

60
61
62def solve_puzzle(
63 initial_board: List[List[int]], goal_board: List[List[int]]
64) -> Optional[PuzzleState]:
65 """
66 Solve 8-puzzle using A* algorithm.
67
68 >>> solve_puzzle([[1,2,3],[4,0,5],[7,8,6]], [[1,2,3],[4,5,6],[7,8,0]]) is not None
69 True
70 """
71 initial = PuzzleState(initial_board, goal_board)
72 frontier = PriorityQueue()
73 frontier.put(initial)
74 explored: Set[Tuple[Tuple[int, ...], ...]] = set()
75
76 while not frontier.empty():
77 current = frontier.get()
78 if current.is_goal():
79 return current
80 explored.add(tuple(map(tuple, current.board)))
81 for neighbor in current.neighbors():
82 if tuple(map(tuple, neighbor.board)) not in explored:
83 frontier.put(neighbor)
84 return None
85
86
87def print_solution(solution: Optional[PuzzleState]) -> None:

Callers

nothing calls this directly

Calls 5

PuzzleStateClass · 0.85
is_goalMethod · 0.80
neighborsMethod · 0.80
getMethod · 0.45
addMethod · 0.45

Tested by

no test coverage detected