Skip to content
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
26 changes: 26 additions & 0 deletions Breadth First search
Original file line number Diff line number Diff line change
@@ -0,0 +1,26 @@
import collections

# BFS algorithm
def bfs(graph, root):

visited, queue = set(), collections.deque([root])
visited.add(root)

while queue:

# Dequeue a vertex from queue
vertex = queue.popleft()
print(str(vertex) + " ", end="")

# If not visited, mark it as visited, and
# enqueue it
for neighbour in graph[vertex]:
if neighbour not in visited:
visited.add(neighbour)
queue.append(neighbour)


if __name__ == '__main__':
graph = {0: [1, 2], 1: [2], 2: [3], 3: [1, 2]}
print("Following is Breadth First Traversal: ")
bfs(graph, 0)