Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Created shortest path using bfs #794

Merged
merged 2 commits into from
May 17, 2019
Merged
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
43 changes: 43 additions & 0 deletions graphs/bfs-shortestpath.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,43 @@
graph = {'A': ['B', 'C', 'E'],
'B': ['A','D', 'E'],
'C': ['A', 'F', 'G'],
'D': ['B'],
'E': ['A', 'B','D'],
'F': ['C'],
'G': ['C']}

def bfs_shortest_path(graph, start, goal):
# keep track of explored nodes
explored = []
# keep track of all the paths to be checked
queue = [[start]]

# return path if start is goal
if start == goal:
return "That was easy! Start = goal"

# keeps looping until all possible paths have been checked
while queue:
# pop the first path from the queue
path = queue.pop(0)
# get the last node from the path
node = path[-1]
if node not in explored:
neighbours = graph[node]
# go through all neighbour nodes, construct a new path and
# push it into the queue
for neighbour in neighbours:
new_path = list(path)
new_path.append(neighbour)
queue.append(new_path)
# return path if neighbour is goal
if neighbour == goal:
return new_path

# mark node as explored
explored.append(node)

# in case there's no path between the 2 nodes
return "So sorry, but a connecting path doesn't exist :("

bfs_shortest_path(graph, 'G', 'D') # returns ['G', 'C', 'A', 'B', 'D']
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Thanks. But graph isn't defined on this line and thus it doesn't compile. Also, you may consider to add a few more test cases, like edge cases.