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.

bfs.py 6.6KB

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