I'm trying to check for cycles in a directed graph. In said graph, the nodes consist of only their name, and their parent nodes (if available). For example, a simple node representation could look something similar to this:
class Node:
name: str
parents: list
def __init__(self, name, parents)
self.name = name
self.parents = parents
A simple graph:
graph = [Node("source", []), Node("node1", ["source"]), Node("node2", ["node1", "source"]) ]
A simple graph that has a cycle in it:
graph = [Node("source", []), Node("node1", ["source", "node3"]), Node("node2", ["node1"]), Node("node3", ["node1"])]
I'm struggling to think of a way to properly detect the cycles in these situations. I'd prefer to not have to parse over the graph and create another representation with something like vertices just so I can do cycle detection, so I'm trying to explore if there are other options. I'm familiar with cycle detection algorithms using searches for nodes that have child dependency information.
I've tried to modify DFS approaches to graph searches like the one implemented below but they don't seem to catch the cycles in the graph, given that I'm only given the parent information. https://medium.com/coder-life/detect-cycle-in-a-directed-graph-undirected-graph-dcd788e91b8
I've also reviewed the solutions in Best algorithm for detecting cycles in a directed graph but I'm having a hard time applying them. Specifically, a lot of them seem to rely on having edges and an adjacency representation that allows for parents nodes to point to child nodes, but is there a way to check for cycles without having parent nodes point to their children?