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

Add code for breadth first algorithm #111

Open
wants to merge 1 commit into
base: master
Choose a base branch
from
Open
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
39 changes: 39 additions & 0 deletions SearchingAlgorithms/GraphSearch/breadth_first_search.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,39 @@
graph = {'A': set(['B', 'C']),
'B': set(['A', 'D', 'E']),
'C': set(['A', 'F']),
'D': set(['B']),
'E': set(['B', 'F']),
'F': set(['C', 'E'])
}

# here A,B,....,F represents each node and nodes inside set are the one which are connected with main node


def bfs_paths(graph, start, goal):
"""
:param graph: complete nodes and vertices are given
:param start: Starting point
:param goal: Ending point
:return: shortest path for the given graph
"""

queue = [(start, [start])]
while queue:
(vertex, path) = queue.pop(0)
for next in graph[vertex] - set(path):
if next == goal:
yield path + [next]
else:
queue.append((next, path + [next]))


def shortest_path(graph, start, goal):
try:
return next(bfs_paths(graph, start, goal))
except StopIteration:
return None

if __name__ == '__main__':

result = shortest_path(graph, 'A', 'F')
print "shortest path is: ", ' -> '.join(result)