I've seen other questions about depth first search but my problem is slightly different and I really don't get it. In prolog, I represent my undirected graph like this:
[0-[1,5], 1-[0,2], 2-[1,3], 3-[2,0], 5-[0]]
Which is a set of key-value, where the key represents the node and the list: -[] represents its neighbors.
I don't know how to do a depth first search with this model. I've tried many solution. I want a really basic recursive algorithm like this one:
dfs(v, visited):
if visited[v] then return
visited.insert(v)
foreach neighbor of v:
dfs(neighbor, visited)
What I can't do in prolog is pass visited as a mutable reference which will be modified by each neighbor for the next neighbor recursively.
Because If I translate it into prolog:
% here Graph contains the entire key-value pairs list,
% Node-Neighbor is the current node with its neighbors.
dfs(Graph, Node-Neighbors, Visited) :-
\+ member(Node, Visisted),
% Now here I could get the next neighbor within neighbor, like so:
member(Node1,Neighbors),
% Then gets its own neighbors too by:
member(Node1-Neighbors1, Graph),
% but here I'm stuck...
I would need some kind of folding where each neighbors call dfs and its result is passed to the next neighbors, but I don't know how to do that...
Thanks.
Visitedand the output one. Take the set union of the output Visited sets of your neighbors plus yourself and that's the output Visited. - Daniel Lyons