‣
‣
‣
‣
‣
‣
class Graph:
# Constructor
def __init__(self):
# default dictionary to store graph
self.graph = defaultdict(list)
# function to add an edge to graphdef addEdge(self,u,v):
self.graph[u].append(v)
# function to print a BFS of graph
def BFS(self, v):
V = self.graph
# Mark all the vertices as not visited
visited = [False] * (len(V))
# Create a queue for BFS
queue = []
# Mark the source node as
# visited and enqueue it
queue.append(v)
visited[v] = True
while queue:
# Dequeue a vertex from
# queue and print it
s = queue.pop(0)
print (s, end = " ") # additional logic here!
# Get all adjacent vertices of the
# dequeued vertex s. If a adjacent
# has not been visited, then mark it
# visited and enqueue it
neighbors = self.graph[n]
for n in neighbors:
if not visited[n]:
queue.append(n)
visited[v] = True
class Graph:
def __init__(self):
self.graph = defaultdict(list)
def addEdge(self,u,v):
self.graph[u].append(v)
def BFS(self, v):
V = self.graph
visited = [False] * (len(V))
queue = []
queue.append(v)
visited[v] = True
while queue:
s = queue.pop(0)
print (s, end = " ")
# additional logic here!
neighbors = self.graph[n]
for n in neighbors:
if not visited[n]:
queue.append(n)
visited[v] = True