You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

graph.py 7.6KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211
  1. from collections import deque
  2. from typing import List
  3. import re
  4. from enum import Enum
  5. class NodeColor(Enum):
  6. """Enumeration for node colors in a graph traversal."""
  7. WHITE = 1 # WHITE: not visited
  8. GRAY = 2 # GRAY: visited but not all neighbors visited
  9. BLACK = 3 # BLACK: visited and all neighbors visited
  10. class Vertex:
  11. """A vertex in a graph."""
  12. def __init__(self, value):
  13. self.value = value
  14. def __repr__(self):
  15. return str(self.value)
  16. class Graph:
  17. """A graph."""
  18. def insert_vertex(self, name: str):
  19. raise NotImplementedError("Please implement this method in subclass")
  20. def connect(self, name1: str, name2: str, weight: float = 1):
  21. raise NotImplementedError("Please implement this method in subclass")
  22. def all_vertices(self) -> List[Vertex]:
  23. raise NotImplementedError("Please implement this method in subclass")
  24. def get_vertex(self, name: str) -> Vertex:
  25. raise NotImplementedError("Please implement this method in subclass")
  26. def get_adjacent_vertices(self, name: str) -> List[Vertex]:
  27. raise NotImplementedError("Please implement this method in subclass")
  28. def get_adjacent_vertices_with_weight(self, name: str) -> List[tuple[Vertex, float]]:
  29. raise NotImplementedError("Please implement this method in subclass")
  30. def bfs(self, start_name: str):
  31. """
  32. Perform a breadth-first search starting at the given vertex.
  33. :param start_name: the name of the vertex to start at
  34. :return: a tuple of two dictionaries, the first mapping vertices to distances from the start vertex,
  35. the second mapping vertices to their predecessors in the traversal tree
  36. """
  37. color_map = {} # maps vertices to their color
  38. distance_map = {} # maps vertices to their distance from the start vertex
  39. predecessor_map = {} # maps vertices to their predecessor in the traversal tree
  40. # Initialize the maps
  41. for vertex in self.all_vertices():
  42. color_map[vertex] = NodeColor.WHITE
  43. distance_map[vertex] = None
  44. predecessor_map[vertex] = None
  45. # Start at the given vertex
  46. start_node = self.get_vertex(start_name)
  47. color_map[start_node] = NodeColor.GRAY
  48. distance_map[start_node] = 0
  49. # Initialize the queue with the start vertex
  50. queue = deque()
  51. queue.append(start_node)
  52. # Process the queue
  53. while len(queue) > 0:
  54. vertex = queue.popleft()
  55. for dest in self.get_adjacent_vertices(vertex.value):
  56. if color_map[dest] == NodeColor.WHITE:
  57. color_map[dest] = NodeColor.GRAY
  58. distance_map[dest] = distance_map[vertex] + 1
  59. predecessor_map[dest] = vertex
  60. queue.append(dest)
  61. color_map[vertex] = NodeColor.BLACK
  62. # Return the distance and predecessor maps
  63. return distance_map, predecessor_map
  64. def path(self, destination, map):
  65. """
  66. Compute the path from the start vertex to the given destination vertex.
  67. The map parameter is the predecessor map
  68. """
  69. path = []
  70. destination_node = self.get_vertex(destination)
  71. while destination_node is not None:
  72. path.insert(0, destination_node.value)
  73. destination_node = map[destination_node]
  74. return path
  75. class AdjacencyListGraph(Graph):
  76. """A graph implemented as an adjacency list."""
  77. def __init__(self):
  78. self.adjacency_map = {} # maps vertex names to lists of adjacent vertices
  79. self.vertex_map = {} # maps vertex names to vertices
  80. def insert_vertex(self, name: str):
  81. if name not in self.vertex_map:
  82. self.vertex_map[name] = Vertex(name)
  83. if name not in self.adjacency_map:
  84. self.adjacency_map[name] = []
  85. def connect(self, name1: str, name2: str, weight: float = 1):
  86. adjacency_list = self.adjacency_map[name1]
  87. dest = self.vertex_map[name2]
  88. adjacency_list.append((dest, weight))
  89. def all_vertices(self) -> List[Vertex]:
  90. return list(self.vertex_map.values())
  91. def get_vertex(self, name: str) -> Vertex:
  92. return self.vertex_map[name]
  93. def get_adjacent_vertices(self, name: str) -> List[Vertex]:
  94. return list(map(lambda x: x[0], self.adjacency_map[name]))
  95. def get_adjacent_vertices_with_weight(self, name: str) -> List[tuple[Vertex, float]]:
  96. return self.adjacency_map[name]
  97. class AdjacencyMatrixGraph(Graph):
  98. """A graph implemented as an adjacency matrix."""
  99. def __init__(self):
  100. self.index_map = {} # maps vertex names to indices
  101. self.vertex_list = [] # list of vertices
  102. self.adjacency_matrix = [] # adjacency matrix
  103. def insert_vertex(self, name: str):
  104. if name not in self.index_map:
  105. self.index_map[name] = len(self.vertex_list)
  106. self.vertex_list.append(Vertex(name))
  107. for row in self.adjacency_matrix: # add a new column to each row
  108. row.append(None)
  109. self.adjacency_matrix.append([None] * len(self.vertex_list)) # add a new row
  110. def connect(self, name1: str, name2: str, weight: float = 1):
  111. index1 = self.index_map[name1]
  112. index2 = self.index_map[name2]
  113. self.adjacency_matrix[index1][index2] = weight
  114. def all_vertices(self) -> List[Vertex]:
  115. return self.vertex_list
  116. def get_vertex(self, name: str) -> Vertex:
  117. index = self.index_map[name]
  118. return self.vertex_list[index]
  119. def get_adjacent_vertices(self, name: str) -> List[Vertex]:
  120. index = self.index_map[name]
  121. result = []
  122. for i in range(len(self.vertex_list)):
  123. if self.adjacency_matrix[index][i] is not None:
  124. name = self.vertex_list[i].value
  125. result.append(self.get_vertex(name))
  126. return result
  127. def get_adjacent_vertices_with_weight(self, name: str) -> List[tuple[Vertex, float]]:
  128. index = self.index_map[name]
  129. result = []
  130. for i in range(len(self.vertex_list)):
  131. if self.adjacency_matrix[index][i] is not None:
  132. name = self.vertex_list[i].value
  133. result.append((self.get_vertex(name), self.adjacency_matrix[index][i]))
  134. return result
  135. if __name__ == "__main__":
  136. def read_cave_into_graph(graph: Graph, filename: str):
  137. """Read a cave description from a file and insert it into the given graph."""
  138. with open(filename, "r") as file:
  139. lines = file.readlines()
  140. for line in lines:
  141. # match a line with two node names and an optional direction
  142. m = re.match(r"(^\s*\"(.*)\"\s*([<>]*)\s*\"(.*)\"\s*)", line)
  143. if m:
  144. startnode = m.group(2)
  145. endnode = m.group(4)
  146. opcode = m.group(3)
  147. graph.insert_vertex(startnode)
  148. graph.insert_vertex(endnode)
  149. if '>' in opcode:
  150. graph.connect(startnode, endnode)
  151. if '<' in opcode:
  152. graph.connect(endnode, startnode)
  153. graph = AdjacencyListGraph()
  154. #graph = AdjacencyMatrixGraph()
  155. read_cave_into_graph(graph, "../../hoehle.txt")
  156. _, predecessor_map = graph.bfs('Höhleneingang')
  157. path = graph.path('Schatzkammer', predecessor_map)
  158. print(path)
  159. _, predecessor_map = graph.bfs('Schatzkammer')
  160. path = graph.path('Höhleneingang', predecessor_map)
  161. print(path)