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

Breadth First Search Implementation in Python #242

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
42 changes: 42 additions & 0 deletions python/breadthFirstSearch.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,42 @@
from queue import Queue

adj_list = {
"A": ["B", "D"],
"B": ["A", "C"],
"C": ["B"],
"D": ["A", "E", "F"],
"E": ["D", "F","G" ],
"F": ["D", "E", "H"],
"G": ["E", "H"],
"H": ["G", "F"]
}

#bfs code
visited = {}
level = {}
parent = {}
bfs_traversal_output = []
queue = Queue()

for node in adj_list.keys():
visited[node] = False
parent[node] = None
level[node] = -1

s= "A"
visited[s] = True
level[s] = 0
queue.put(s)

while not queue.empty():
u = queue.get()
bfs_traversal_output.append(u)

for v in adj_list[u]:
if not visited[v]:
visited[v] = True
parent[v] = u
level[v] = level[u] +1
queue.put(v)

print(bfs_traversal_output)