Skip to content

Commit b453fe5

Browse files
authored
Breadth first search
Bfs algorithm in Python
1 parent 229f8d6 commit b453fe5

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)