Task: Do DFS traversal from a given given graph and print output.
Is this code the correct implementation of DFS traversal in Graph?
from collections import defaultdict
class Graph(object):
def __init__(self):
self.graph = defaultdict(list)
def add_edge(self, u, v):
self.graph[u].append(v)
def depth_first_search(self,node):
visited = []
stack = [node]
while stack:
node = stack.pop()
if node not in visited:
print node
visited.append(node)
for i in self.graph[node]:
stack.append(i)
G = Graph()
G.add_edge(1,2)
G.add_edge(1,4)
G.add_edge(1,5)
G.add_edge(2,3)
G.add_edge(3,5)
G.depth_first_search(1)
visited
aslist
you could have it as aset
. Which will improve yourin
lookup fromO(N)
toO(1)
\$\endgroup\$