1

I'm a newbie in Prolog and I'm stuck with this exercise, can you give me some advices on how to solve it in a simple way?

Given a graph, find any path from Node1 to Node2 and return a list of the paths, if the paths are many they have to be shown one by one, as in the example output. A path from N1 to N2 exists if there is a e(N1,N2). A path from N1 to N2 is valid if N3 can be reached from N1, and then there is a path from N2 to N3, recursively.

find_any_path(+Graph, +Node1, +Node2, -ListPath)

The output expected should be as the following:

find_any_path([e(1,2),e(1,3),e(2,3)],1,3,L).
– L/[e(1,2),e(2,3)]
– L/[e(1,3)]

Here's my implementation

reaching([], N, []):-!.
reaching(G, N, L):-findall(X, member(e(N,X), G), L).

dropAny(X,[X|T],T).
dropAny(X,[H|Xs],[H|L]):-dropAny(X,Xs,L).

find_any_path([],N1,N2,[]).
find_any_path(G,N1,N2,L):-  member(e(N1,N2),G),
                            reaching(G,N1,R), %R=[2,3]
                            dropAny(N2,R,M), %M=[2] numbers found between N1 and N3
                            anypath(G,N1,N2,M,L).

find_any_path(G,N1,N2,[],[e(N1,N2)]).
find_any_path(G,N1,N2,[M|Ms],[e(N1,M),e(M,N2)|L]):- member(e(M,N2),G),
                                                find_any_path(G,N1,N2,Ms,L).

The output shown is the following, different from the expected result :

L / [e(1,2),e(2,3),e(1,3)]
Guy Coder
  • 24,501
  • 8
  • 71
  • 136
Kwr93
  • 59
  • 1
  • 9
  • Interesting problem. What have you tried? Do you have a more specific question? You can search this site for "[prolog] graph path" or something similar and find lots of examples. – lurker Aug 30 '18 at 01:12
  • @lurker I cannot seem to find any example that could suit the problem. I added my implementation to the question. – Kwr93 Sep 03 '18 at 12:05
  • What do you mean by `L / [...]`? Do you mean `L = [...]`? – lurker Sep 03 '18 at 17:02
  • Yes, I mean `L = [...]` – Kwr93 Sep 10 '18 at 14:22

0 Answers0