~/ learn/ comp-456/ cards/ Prolog for graph search: paths and cycle checking
1 of 4

Type the edge facts and the acyclic path finder

Type the edge facts and the acyclic path finder

Answer

edge(a,b). edge(a,c). edge(b,d). edge(c,d). edge(d,e). path(G, G, V, P) :- reverse(V, P). path(N, G, V, P) :- edge(N, Nx), \+ member(Nx, V), path(Nx, G, [Nx|V], P).

Base case: current node equals goal G, so reverse the accumulated visited list V into the forward path P. Recursive step: take an edge N->Nx, require Nx is unvisited (the cycle guard), and recurse with Nx prepended. Prepend-then-reverse keeps each step O(1).

space flip · ← → navigate · esc to exit
NORMAL ~/memra/library/c8dd5aa7-e75b-4340-94ab-fa9d3e6eb4e1/flashcard utf-8 LF