1
+ """Breath First Search (BFS) can be used when finding the shortest path
2
+ from a given source node to a target node in an unweighted graph.
3
+ """
1
4
class Graph :
2
5
def __init__ (self , graph , source_vertex ):
3
- """graph is implemented as dictionary of adjancency lists"""
6
+ """Graph is implemented as dictionary of adjancency lists. Also,
7
+ Source vertex have to be defined upon initialization.
8
+ """
4
9
self .graph = graph
5
10
# mapping node to its parent in resulting breadth first tree
6
11
self .parent = {}
7
12
self .source_vertex = source_vertex
8
13
9
14
def breath_first_search (self ):
10
- """
15
+ """This function is a helper for running breath first search on this graph.
11
16
"""
12
17
visited = {self .source_vertex }
13
18
self .parent [self .source_vertex ] = None
@@ -21,14 +26,18 @@ def breath_first_search(self):
21
26
self .parent [adjancent_vertex ] = vertex
22
27
queue .append (adjancent_vertex )
23
28
24
- def print_shortest_path (self , target_vertex ):
29
+ def shortest_path (self , target_vertex ):
30
+ """This shortest path function returns a string, describing the result:
31
+ 1.) No path is found. The string is a human readable message to indicate this.
32
+ 2.) The shortest path is found. The string is in the form `v1(->v2->v3->...->vn)`,
33
+ where v1 is the source vertex and vn is the target vertex, if it exists seperately.
34
+ """
25
35
if target_vertex == self .source_vertex :
26
- print ( self .source_vertex , end = "" )
36
+ return f" { self .source_vertex } "
27
37
elif target_vertex not in self .parent or not self .parent [target_vertex ]:
28
- print ( f"No path from vertex:{ self .source_vertex } to vertex:{ target_vertex } " )
38
+ return f"No path from vertex:{ self .source_vertex } to vertex:{ target_vertex } "
29
39
else :
30
- self .print_shortest_path (self .parent [target_vertex ])
31
- print (f"->{ target_vertex } " , end = "" )
40
+ return self .shortest_path (self .parent [target_vertex ]) + f"->{ target_vertex } "
32
41
33
42
34
43
if __name__ == "__main__" :
@@ -43,8 +52,6 @@ def print_shortest_path(self, target_vertex):
43
52
}
44
53
g = Graph (graph , "G" )
45
54
g .breath_first_search ()
46
- g .print_shortest_path ("D" )
47
- print ()
48
- g .print_shortest_path ("G" )
49
- print ()
50
- g .print_shortest_path ("Foo" )
55
+ print (g .shortest_path ("D" ))
56
+ print (g .shortest_path ("G" ))
57
+ print (g .shortest_path ("Foo" ))
0 commit comments