Skip to content

Commit f3608ac

Browse files
dubesarpoyea
authored andcommitted
Created shortest path using bfs (TheAlgorithms#794)
* Created shortest path using bfs
1 parent 5b86928 commit f3608ac

File tree

1 file changed

+43
-0
lines changed

1 file changed

+43
-0
lines changed

graphs/bfs-shortestpath.py

+43
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,43 @@
1+
graph = {'A': ['B', 'C', 'E'],
2+
'B': ['A','D', 'E'],
3+
'C': ['A', 'F', 'G'],
4+
'D': ['B'],
5+
'E': ['A', 'B','D'],
6+
'F': ['C'],
7+
'G': ['C']}
8+
9+
def bfs_shortest_path(graph, start, goal):
10+
# keep track of explored nodes
11+
explored = []
12+
# keep track of all the paths to be checked
13+
queue = [[start]]
14+
15+
# return path if start is goal
16+
if start == goal:
17+
return "That was easy! Start = goal"
18+
19+
# keeps looping until all possible paths have been checked
20+
while queue:
21+
# pop the first path from the queue
22+
path = queue.pop(0)
23+
# get the last node from the path
24+
node = path[-1]
25+
if node not in explored:
26+
neighbours = graph[node]
27+
# go through all neighbour nodes, construct a new path and
28+
# push it into the queue
29+
for neighbour in neighbours:
30+
new_path = list(path)
31+
new_path.append(neighbour)
32+
queue.append(new_path)
33+
# return path if neighbour is goal
34+
if neighbour == goal:
35+
return new_path
36+
37+
# mark node as explored
38+
explored.append(node)
39+
40+
# in case there's no path between the 2 nodes
41+
return "So sorry, but a connecting path doesn't exist :("
42+
43+
bfs_shortest_path(graph, 'G', 'D') # returns ['G', 'C', 'A', 'B', 'D']

0 commit comments

Comments
 (0)