MCPcopy Index your code
hub / github.com/TheAlgorithms/Python / Graph

Class Graph

graphs/breadth_first_search_shortest_path.py:18–82  ·  view source on GitHub ↗

Source from the content-addressed store, hash-verified

16
17
18class Graph:
19 def __init__(self, graph: dict[str, list[str]], source_vertex: str) -> None:
20 """
21 Graph is implemented as dictionary of adjacency lists. Also,
22 Source vertex have to be defined upon initialization.
23 """
24 self.graph = graph
25 # mapping node to its parent in resulting breadth first tree
26 self.parent: dict[str, str | None] = {}
27 self.source_vertex = source_vertex
28
29 def breath_first_search(self) -> None:
30 """
31 This function is a helper for running breath first search on this graph.
32 >>> g = Graph(graph, "G")
33 >>> g.breath_first_search()
34 >>> g.parent
35 {'G': None, 'C': 'G', 'A': 'C', 'F': 'C', 'B': 'A', 'E': 'A', 'D': 'B'}
36 """
37 visited = {self.source_vertex}
38 self.parent[self.source_vertex] = None
39 queue = [self.source_vertex] # first in first out queue
40
41 while queue:
42 vertex = queue.pop(0)
43 for adjacent_vertex in self.graph[vertex]:
44 if adjacent_vertex not in visited:
45 visited.add(adjacent_vertex)
46 self.parent[adjacent_vertex] = vertex
47 queue.append(adjacent_vertex)
48
49 def shortest_path(self, target_vertex: str) -> str:
50 """
51 This shortest path function returns a string, describing the result:
52 1.) No path is found. The string is a human readable message to indicate this.
53 2.) The shortest path is found. The string is in the form
54 `v1(->v2->v3->...->vn)`, where v1 is the source vertex and vn is the target
55 vertex, if it exists separately.
56
57 >>> g = Graph(graph, "G")
58 >>> g.breath_first_search()
59
60 Case 1 - No path is found.
61 >>> g.shortest_path("Foo")
62 Traceback (most recent call last):
63 ...
64 ValueError: No path from vertex: G to vertex: Foo
65
66 Case 2 - The path is found.
67 >>> g.shortest_path("D")
68 'G->C->A->B->D'
69 >>> g.shortest_path("G")
70 'G'
71 """
72 if target_vertex == self.source_vertex:
73 return self.source_vertex
74
75 target_vertex_parent = self.parent.get(target_vertex)

Calls

no outgoing calls

Tested by

no test coverage detected