Skip to content

Commit 560978d

Browse files
Merge pull request seeditsolution#262 from Naveen963/patch-3
Breadth first search
2 parents 79c78fc + b453fe5 commit 560978d

File tree

1 file changed

+26
-0
lines changed

1 file changed

+26
-0
lines changed

Breadth First search

+26
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,26 @@
1+
import collections
2+
3+
# BFS algorithm
4+
def bfs(graph, root):
5+
6+
visited, queue = set(), collections.deque([root])
7+
visited.add(root)
8+
9+
while queue:
10+
11+
# Dequeue a vertex from queue
12+
vertex = queue.popleft()
13+
print(str(vertex) + " ", end="")
14+
15+
# If not visited, mark it as visited, and
16+
# enqueue it
17+
for neighbour in graph[vertex]:
18+
if neighbour not in visited:
19+
visited.add(neighbour)
20+
queue.append(neighbour)
21+
22+
23+
if __name__ == '__main__':
24+
graph = {0: [1, 2], 1: [2], 2: [3], 3: [1, 2]}
25+
print("Following is Breadth First Traversal: ")
26+
bfs(graph, 0)

0 commit comments

Comments
 (0)