I am wiring a function to check whether a graph contains a cycle.
It is represented as a list of lists of all indexes of nodes each node is connected to. Nodes are enumerated from 1 (task requirement).
While checking the graph [[2, 3], [], [4], []], the program enters the first listed node correctly, yet in the second iteration, it is assumed that adjlist[node-1] is an int of value 3 rather than an array (or int = 2 at very least)
What am I missing?
The code:
def is_acyclic(adjlist: List, visited: List, path: List) -> bool:
'''
:param adjlist: list representation of a graph; eg: [[2, 3], [], [4], []]
:param visited: visited nodes
:param path: visited nodes in current iteration
:return: the graph does not contain a cycle
'''
for node in range(1, len(adjlist)+1):
if node not in visited:
visited.append(node)
path.append(node)
for child in adjlist[node-1]:
if child in path:
return False
elif child not in visited:
if is_acyclic(adjlist[node-1], visited, path) is False:
return False
path.remove(node)
return True