I have a directed multigraph with no self-loops:
What's the most efficient way to mark nodes 1, 2 and 3 as being members of a cycle?
My first thought would be to
- Perform a depth-first search starting from an arbitrary node
- Push all nodes I've seen in a given branch into a "seen" array. Also, mark each node as "checked".
- For each new node, check if any of its children are in the seen array
- If it is, mark each node in the array between the seen node and its previous occurrence as seen
- While traveling down the DFS, make sure to skip any children who have been seen
- Repeat 1-5 with the next node that hasn't been marked as "checked" yet (since I may have disconnected regions of the graph)
This seems like it might work, but wonder if it's the most efficient way, give that I've got to maintain an array of "seen" nodes, and, since this has to be called recursively, I think I may be doing a lot of array modification (e.g. at one point in my algorithm I'll have [0,1,2,3,1] and another point I'll have [0,1,2,3,4], for the graph above, so it's not just "build once"). I also have to go through the list an additional time at the start to removed the "checked" mark that may have been left over from a previous test.