Professional Documents
Culture Documents
Theory:
Conduct Depth-First Search (DFS) in Prolog to locate a path from a starting node to a
goal node within a graph.
Utilize dfs(Node, Goal, Path) as the main predicate to initiate the DFS search. It aims to
discover a path from the given Node to the desired Goal.
Establish a base case with dfs_stack_temp(Node, Node, _, [Node]) :- !.. This rule
terminates the search when the current Node matches the Goal, forming the final path.
Implement dfs_stack_temp(Node, Goal, Visited, [Node | Path]) for traversing. It
recursively explores adjacent nodes (Next) from the current Node, while also ensuring
that previously visited nodes are not revisited (Visited).
Utilize the edge(Node, Next) predicate to define connections between nodes in the graph.
Ensure that already visited nodes are not revisited to prevent infinite loops in cyclic
graphs. This is achieved using \+ member(Next, Visited).
Define the graph structure using edge/2 facts or rules. Subsequently, invoke dfs/3 with
the starting node, the goal node, and an unbound variable to collect the resulting path.
The DFS search concludes once the goal node is reached, thereby returning the path
leading to it.
Source Code:
edge(a, d).
edge(a, c).
edge(a, b).
edge(d, f).
edge(d, e).
edge(c, g).
edge(b, h).
edge(b, i).
dfs(Node, Goal, Path) :-
dfs_stack_temp(Node, Goal, [Node], Path).
dfs_stack_temp(Node, Node, _, [Node]) :- !.
dfs_stack_temp(Node, Goal, Visited, [Node | Path]) :-
edge(Node, Next),
\+ member(Next, Visited),
dfs_stack_temp(Next, Goal, [Next | Visited], Path).
Output: