Skip to content

Commit 86e56e0

Browse files
authored
Merge pull request faif#350 from LCVcode/master
Implemented breadth first search for shortest graph path in graph_search.py
2 parents eeb9711 + 62e6fd5 commit 86e56e0

File tree

1 file changed

+35
-7
lines changed

1 file changed

+35
-7
lines changed

patterns/other/graph_search.py

Lines changed: 35 additions & 7 deletions
Original file line numberDiff line numberDiff line change
@@ -1,12 +1,15 @@
11
class GraphSearch:
22

33
"""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"""
58

69
def __init__(self, graph):
710
self.graph = graph
811

9-
def find_path(self, start, end, path=None):
12+
def find_path_dfs(self, start, end, path=None):
1013
path = path or []
1114

1215
path.append(start)
@@ -18,7 +21,7 @@ def find_path(self, start, end, path=None):
1821
if newpath:
1922
return newpath
2023

21-
def find_all_path(self, start, end, path=None):
24+
def find_all_paths_dfs(self, start, end, path=None):
2225
path = path or []
2326
path.append(start)
2427
if start == end:
@@ -30,7 +33,7 @@ def find_all_path(self, start, end, path=None):
3033
paths.extend(newpaths)
3134
return paths
3235

33-
def find_shortest_path(self, start, end, path=None):
36+
def find_shortest_path_dfs(self, start, end, path=None):
3437
path = path or []
3538
path.append(start)
3639

@@ -45,6 +48,29 @@ def find_shortest_path(self, start, end, path=None):
4548
shortest = newpath
4649
return shortest
4750

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+
4874

4975
def main():
5076
"""
@@ -54,12 +80,14 @@ def main():
5480
# initialization of new graph search object
5581
>>> graph1 = GraphSearch(graph)
5682
57-
>>> print(graph1.find_path('A', 'D'))
83+
>>> print(graph1.find_path_dfs('A', 'D'))
5884
['A', 'B', 'C', 'D']
59-
>>> print(graph1.find_all_path('A', 'D'))
85+
>>> print(graph1.find_all_paths_dfs('A', 'D'))
6086
[['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'))
6288
['A', 'B', 'D']
89+
>>> print(graph1.find_shortest_path_bfs('A', 'D'))
90+
['A', 'B', 'C']
6391
"""
6492

6593

0 commit comments

Comments
 (0)