Reputation: 11
https://i.ibb.co/q0zXPGv/qe.jpg
In Prolog, we can introduce a predicate about edge direction to represent the above graph:
edge(s,a).
edge(a,b).
We further introduce a predicate about node connectivity:
connected(X,Y) :- edge(X,Y).
connected(X,Y) :- edge(X,Z), connected(Z,Y).
Now, we would like to further extend our program with a predicate path(X,Y,P)
which will use variable P
to hold a list of nodes which constitute a valid path from node X
to node Y
.
Implement the path predicate and write the answer of the Prolog system to the following queries:
1. ?- path(s,f,P).
2. ?- path(d,c,P).
3. ?- path(s,g,P).
4. ?- path(s,e,P).
Image of path
Upvotes: 0
Views: 335
Reputation: 71
Let's check my solution to the problem:
edge(s,a).
edge(s,f).
edge(s,e).
edge(f,e).
edge(a,b).
edge(e,d).
edge(d,a).
edge(d,c).
edge(b,c).
edge(c,g).
connected(X,Y):- edge(X,Y).
connected(X,Y):- edge(X,Z), connected(Z,Y).
path(X,X,[X]).
path(X,Y,[X|P]):- connected(X,Z), path(Z,Y,P),!.
If the path is from the node to the node itself then the result must be the node. Otherwise, node X should be in the path if we can go from X to Y through some node(s) Z.
I don't really like the implementation of connected because it forces you tou cut the solution.
Hope it helps! Here are the answers to the queries above:
?- path(s,f,P).
P = [s, f].
?- path(d,c,P).
P = [d, a, b, c].
?- path(s,g,P).
P = [s, a, b, c, g].
?- path(s,e,P).
P = [s, f, e].
Upvotes: 1