Browse Source

Lecture 7

master
Oliver Hofmann 5 months ago
parent
commit
4bad896096
1 changed files with 10 additions and 5 deletions
  1. 10
    5
      SoSe24/lec06_graph/astar.py

+ 10
- 5
SoSe24/lec06_graph/astar.py View File

from typing import Callable from typing import Callable
import re import re
from graph import Graph, AdjacencyListGraph, AdjacencyMatrixGraph, NodeColor, Vertex from graph import Graph, AdjacencyListGraph, AdjacencyMatrixGraph, NodeColor, Vertex
import heapq


def a_star(self, start_name: str, end_name: str, heuristic: Callable[[Vertex], float]): def a_star(self, start_name: str, end_name: str, heuristic: Callable[[Vertex], float]):
color_map = {} # maps vertices to their color color_map = {} # maps vertices to their color
return math.inf return math.inf
return distance_map[vertex] + heuristic(vertex) return distance_map[vertex] + heuristic(vertex)


Vertex.__lt__ = lambda self, other: cost(self) < cost(other)

# Initialize the maps # Initialize the maps
for vertex in self.all_vertices(): for vertex in self.all_vertices():
color_map[vertex] = NodeColor.WHITE color_map[vertex] = NodeColor.WHITE
distance_map[start_node] = 0 distance_map[start_node] = 0


# Initialize the queue with the start vertex # Initialize the queue with the start vertex
queue = [start_node]
queue = [] # Use a list instead of a deque, because we need to sort it with
heapq.heappush(queue, start_node)


# Process the queue # Process the queue
while len(queue) > 0: while len(queue) > 0:
queue.sort(key=cost)
vertex = queue.pop(0)
vertex = heapq.heappop(queue)
if color_map[vertex] == NodeColor.BLACK:
# Skip already processed vertices (possibly with a higher cost)
continue
if vertex.value == end_name: if vertex.value == end_name:
# Return the distance and predecessor maps # Return the distance and predecessor maps
return distance_map, predecessor_map return distance_map, predecessor_map
continue continue
predecessor_map[dest] = vertex predecessor_map[dest] = vertex
distance_map[dest] = distance_map[vertex] + weight distance_map[dest] = distance_map[vertex] + weight
heapq.heappush(queue, dest)
if color_map[dest] == NodeColor.WHITE: if color_map[dest] == NodeColor.WHITE:
queue.append(dest)
color_map[dest] = NodeColor.GRAY color_map[dest] = NodeColor.GRAY
color_map[vertex] = NodeColor.BLACK color_map[vertex] = NodeColor.BLACK



Loading…
Cancel
Save