def test_on_field(self): self.assertTrue(p.on_field((4, 4), (3, 3))) self.assertTrue(p.on_field((4, 4), (0, 0))) self.assertFalse(p.on_field((4, 4), (-1, 0))) self.assertFalse(p.on_field((4, 4), (4, 0))) self.assertTrue(p.on_field((4, 4, 2), (0, 0, 0))) self.assertFalse(p.on_field((4, 4, 2), (0, 0, 2)))
def a_star(n, start, goal, obstacles): priority = lambda p: len(p) + puz.manhattan_dist(p[-1], goal) visited = set() frontier = list() q.heappush(frontier, (priority([start]), [start])) while frontier: _, path = q.heappop(frontier) if path[-1] == goal: return path if not path[-1] in visited: visited.add(path[-1]) walkable_neighbors = [nb for nb in puz.direct_neighbors(path[-1]) if puz.on_field((n, n), nb) and nb not in obstacles] # TODO for p in [path + [n] for n in walkable_neighbors]: q.heappush(frontier, (priority(p), p)) return None