From 9945277fd72987ae4afe75c11162b5726b569a97 Mon Sep 17 00:00:00 2001 From: yashkumarjha12 <72943344+yashkumarjha12@users.noreply.github.com> Date: Thu, 6 Oct 2022 12:02:20 +0530 Subject: [PATCH] Create BFS.py --- Python/BFS.py | 20 ++++++++++++++++++++ 1 file changed, 20 insertions(+) create mode 100644 Python/BFS.py diff --git a/Python/BFS.py b/Python/BFS.py new file mode 100644 index 0000000..2fea1a7 --- /dev/null +++ b/Python/BFS.py @@ -0,0 +1,20 @@ +import collections + +def bfs(graph, root): + + visited, queue = set(), collections.deque([root]) + visited.add(root) + + while queue: + vertex = queue.popleft() + print(str(vertex) + " ", end="") + 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)