So, I'm trying to solve a task where I'm supposed to find if there is a cycle in the given graph using DFS. So what im strugguling with now is to match the nodes, since they are of type string I'm having some truble. The error message iI'm getting is the following:
TypeError: list indices must be integers or slices, not Graph
So I'm wondering how to solve this problem, or how to make it work for string and not just int?
graph = dict()
searched = []
def add_edge(self, node, neighbour):
if node not in self.graph:
self.graph[node] = [neighbour]
else:
self.graph[node].append(neighbour)
def depth_first_search(self, node):
if node not in self.searched:
print("[", node, end= " ], ")
self.searched.append(node)
if node in self.graph:
for neighbour in self.graph[node]:
self.depth_first_search(neighbour)
def find_cycle(node):
searched = [False]
for i in searched[node]:
if searched[i] == [False]*node:
if(self.depth_first_search(i, node, neighbour)) == True:
return True
return False
def print_edges(self):
for node in self.graph:
for neighbour in self.graph[node]:
print("(", node, "," , neighbour, ")")
def print_graph(self):
print(self.graph)
my_graph = Graph()
my_graph.add_edge('A', 'B')
my_graph.add_edge('B', 'C')
my_graph.add_edge('B', 'D')
my_graph.add_edge('D', 'E')
my_graph.add_edge('D', 'F')
my_graph.add_edge('C', 'E')
my_graph.add_edge('E', 'G')
my_graph.add_edge('F', 'H')
my_graph.print_graph()
my_graph.print_edges()
my_graph.depth_first_search('A')
result = my_graph.find_cycle()
print(result)