In the given program I have used a stack to implement DFS, with a utility list as stack. This is an iterative approach. The error is here as follows:
---> 19 if visited[i] == False:
IndexError: list index out of range
from collections import defaultdict
class Graph:
def __init__(self):
self.graph = defaultdict(list)
def addEdge(self, u, v):
self.graph[u].append(v)
def dfs_stack(self, start, visited):
stack = []
stack.append(start)
while(len(stack) != 0):
#pop
i = stack.pop()
#if not visited: visit and print
if visited[i] == False: THE ERROR IS ON THIS LINE
visited[i]=True
print(i , end = " ")
#push all unvisited adjacent vertices
for adj in self.graph[i]:
if visited[i] == False:
stack.append(i)
def DFS(self, start):
visited = [False]*(len(self.graph)+1)
self.dfs_stack(start,visited)
g = Graph()
g.addEdge(1, 2)
g.addEdge(2, 3)
g.addEdge(3, 4)
g.addEdge(4, 5)
g.addEdge(5, 1)
g.addEdge(2, 6)
g.addEdge(3, 6)
g.addEdge(8, 7)
g.DFS(8)
== Falseis both unidiomatic and illogical. Also, variable and function names should follow thelower_case_with_underscoresstyle.