1
1
class GraphSearch :
2
2
3
3
"""Graph search emulation in python, from source
4
- http://www.python.org/doc/essays/graphs/"""
4
+ http://www.python.org/doc/essays/graphs/
5
+
6
+ dfs stands for Depth First Search
7
+ bfs stands for Breadth First Search"""
5
8
6
9
def __init__ (self , graph ):
7
10
self .graph = graph
8
11
9
- def find_path (self , start , end , path = None ):
12
+ def find_path_dfs (self , start , end , path = None ):
10
13
path = path or []
11
14
12
15
path .append (start )
@@ -18,7 +21,7 @@ def find_path(self, start, end, path=None):
18
21
if newpath :
19
22
return newpath
20
23
21
- def find_all_path (self , start , end , path = None ):
24
+ def find_all_paths_dfs (self , start , end , path = None ):
22
25
path = path or []
23
26
path .append (start )
24
27
if start == end :
@@ -30,7 +33,7 @@ def find_all_path(self, start, end, path=None):
30
33
paths .extend (newpaths )
31
34
return paths
32
35
33
- def find_shortest_path (self , start , end , path = None ):
36
+ def find_shortest_path_dfs (self , start , end , path = None ):
34
37
path = path or []
35
38
path .append (start )
36
39
@@ -45,6 +48,29 @@ def find_shortest_path(self, start, end, path=None):
45
48
shortest = newpath
46
49
return shortest
47
50
51
+ def find_shortest_path_bfs (self , start , end ):
52
+ queue = [start ]
53
+ dist_to = {start : 0 }
54
+ edge_to = {}
55
+
56
+ while len (queue ):
57
+ value = queue .pop (0 )
58
+ for node in self .graph [value ]:
59
+ if node not in dist_to .keys ():
60
+ edge_to [node ] = value
61
+ dist_to [node ] = dist_to [value ] + 1
62
+ queue .append (node )
63
+ if end in edge_to .values ():
64
+ break
65
+
66
+ path = []
67
+ node = end
68
+ while dist_to [node ] != 0 :
69
+ path .insert (0 , node )
70
+ node = edge_to [node ]
71
+ path .insert (0 , start )
72
+ return path
73
+
48
74
49
75
def main ():
50
76
"""
@@ -54,12 +80,14 @@ def main():
54
80
# initialization of new graph search object
55
81
>>> graph1 = GraphSearch(graph)
56
82
57
- >>> print(graph1.find_path ('A', 'D'))
83
+ >>> print(graph1.find_path_dfs ('A', 'D'))
58
84
['A', 'B', 'C', 'D']
59
- >>> print(graph1.find_all_path ('A', 'D'))
85
+ >>> print(graph1.find_all_paths_dfs ('A', 'D'))
60
86
[['A', 'B', 'C', 'D'], ['A', 'B', 'D'], ['A', 'C', 'D']]
61
- >>> print(graph1.find_shortest_path ('A', 'D'))
87
+ >>> print(graph1.find_shortest_path_dfs ('A', 'D'))
62
88
['A', 'B', 'D']
89
+ >>> print(graph1.find_shortest_path_bfs('A', 'D'))
90
+ ['A', 'B', 'C']
63
91
"""
64
92
65
93
0 commit comments