Search code examples
prologgraph-theorygraph-algorithmpath-finding

undirected graph


How can I find all way to go end in undirected graph ?

Graph :

    Node : S, Y, F, T                visualization :    S ----- Y ---- T
    Edge : S --- Y                                       \     /
           Y --- F                                        \   /
           S --- F                                         \ /
           Y --- T                                          F


Assume that

       Start   S 
       Finish  F

       after run   go 

       result will be :

              S F
              S Y F

I do not want visit one node more than once. If I visit, this problem become one of NP problems.

EDIT:

input can be any form

example:

       edge (S,Y).     OR          edge (Y,S).
       edge (Y,F).                 edge (F,Y).
       edge (S,F).                 edge (F,S).
       edge (Y,T).                 edge (T,Y).

BUT OUTPUT MUST BE SAME


Solution

  • Keep a trace of the visited nodes and exclude those when adding the possible destinations in the next step.

    I changed a few edges and added one, to make sure it also works when edges are listed in the 'wrong' order for going from S to F.

    edge('S','Y').    visualization:    S -- Y -- T
    edge('F','Y').                     / \  /
    edge('S','F').                    /   \/
    edge('Y','T').                   A --- F
    edge('A','S').
    edge('F','A').
    

    In prolog this should roughly look like this:

    pathBetween(A,A,_):- !, fail.
    pathBetween(S,F,Visited) :- (edge(S,F) ; edge(F,S)),
        append(Visited,[S,F],L),
        write(L).
    pathBetween(S,F,Visited) :-
        (   edge(S,A) ; edge(A,S)  ),
        not(member(A,Visited)),
        pathBetween(A,F,[S|Visited]).
    

    You can use ; to manually find all the solutions, or findall.

    ?- findall(Visited, pathBetween('S', 'F', []), _).
    [S,F][S,Y,F][S,A,F]
    true.