I am trying to write a prolog program that detects a cycle in an undirected graph. I have already consulted this question: prolog graph depth first search
and have attempted to alter the dfs algorithm presented there, in order to detect cycles. Here is my progress so far:
findCycle(Node, NextNode, Visited) :-
( member(NextNode, Visited), isNotParent(Node, NextNode) )
->
writeln("found a cycle"), saveCycle(Node, NextNode), !
;
writeln("end of findCycle").
saveCycle(Node, NextNode) :-
% save to structure
dfs(Graph, StartNode) :-
dfs(Graph, StartNode, []).
dfs(Graph, Node, Visited) :-
writeln(Visited),
\+ member(Node, Visited),
write("visiting node "),
write(Node), nl,
member(NextNode, Graph.get(Node)),
% \+ findCycle(Node, NextNode, Visited),
dfs(Graph, NextNode, [Node|Visited]).
The graph in my implementation will be represented as a dictionary, where every key is a vertex, and the corresponding value is a list of all its neighboring vertices. Now, I have a few problems:
I need to be storing the "parent" of each vertex in a data structure, so that it can be used for cycle detection. I am not sure about how to do that. So far I have been testing the program with an example graph, whose edges I enter manually with individual terms. That is not, however, my end goal.
I also need to fix the dfs algorithm, because as it is right now, it causes stack overflow, due to the Visited list not storing all the vertices persistently. Ideally, Visited should be a dictionary instead of a list, so it can be accessed more efficiently.
Finally, if a cycle is detected, I would like to save all the vertices participating in it, into another data structure.
Though I know programming, and have written this program in C++ in the past, my grasp of prolog is at best rudimentary, so any help would be appreciated. Thanks!