From 163dbb66180c9373938c21722ab9182dff886ab7 Mon Sep 17 00:00:00 2001 From: Sahil Agrawal Date: Sat, 19 Oct 2019 17:23:46 +0530 Subject: [PATCH] Create BFS.py --- searching_algo/BFS.py | 42 ++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 42 insertions(+) create mode 100644 searching_algo/BFS.py diff --git a/searching_algo/BFS.py b/searching_algo/BFS.py new file mode 100644 index 0000000..12cd921 --- /dev/null +++ b/searching_algo/BFS.py @@ -0,0 +1,42 @@ +from collections import defaultdict + +#--class for directed graph with adjacency list representation +class Graph: + + #--Constructor of the class + def __init__(self): + #--default dictionary to store graph + self.graph = defaultdict(list) + + ''' + --function to add an edge + --inputs, starting point of the graph + ''' + def addEdge(self,u,v): + self.graph[u].append(v) + + ''' + --to print a BFS of graph + --inputs, starting point of the graph + --Prints the BFS starting from the input point + ''' + def BFS(self, s): + + # Mark all the vertices as not visited + visited = [False] * (len(self.graph)) + + queue = [] + + # Mark the source node as visited and enqueue it + queue.append(s) + visited[s] = True + + while queue: + s = queue.pop(0) + print (s, end = " ") + + for i in self.graph[s]: + if visited[i] == False: + queue.append(i) + visited[i] = True +