class Graph:
def __init__(self, nodes):
self.nodes = nodes
self.edges = 0
self.adj = [[] for i in range(self.nodes)]
def addEdge(self, v, w):
self.adj[v].append(w)
self.edges += 1
def bfs(self, startingNode):
from queue import Queue
seen = [False for i in range(self.nodes)]
q = Queue()
q.put(startingNode)
while not q.empty():
node = q.get()
print(node, end=", ")
seen[node] = True
for neighbour in self.adj[node]:
if not seen[neighbour]:
q.put(neighbour)
We should also learn the time complexity of BFs. This link also provide a better implementation of Breadth First search using python.
ReplyDelete