Browse Source

Create BFS.py

pull/20/head
Sahil Agrawal 4 years ago
committed by GitHub
parent
commit
163dbb6618
No known key found for this signature in database GPG Key ID: 4AEE18F83AFDEB23
1 changed files with 42 additions and 0 deletions
  1. +42
    -0
      searching_algo/BFS.py

+ 42
- 0
searching_algo/BFS.py View File

@ -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

Loading…
Cancel
Save