Find the paths between two given nodes?

前端 未结 8 2130
隐瞒了意图╮
隐瞒了意图╮ 2020-11-27 11:55

Say I have nodes connected in the below fashion, how do I arrive at the number of paths that exist between given points, and path details?

1,2 //node 1 and 2         


        
8条回答
  •  天命终不由人
    2020-11-27 12:31

    In Prolog (specifically, SWI-Prolog)

    :- use_module(library(tabling)).
    
    % path(+Graph,?Source,?Target,?Path)
    :- table path/4.
    
    path(_,N,N,[N]).
    path(G,S,T,[S|Path]) :-
        dif(S,T),
        member(S-I, G), % directed graph
        path(G,I,T,Path).
    

    test:

    paths :- Graph =
        [ 1- 2  % node 1 and 2 are connected
        , 2- 3 
        , 2- 5 
        , 4- 2 
        , 5-11
        ,11-12
        , 6- 7 
        , 5- 6 
        , 3- 6 
        , 6- 8 
        , 8-10
        , 8- 9
        ],
        findall(Path, path(Graph,1,7,Path), Paths),
        maplist(writeln, Paths).
    
    ?- paths.
    [1,2,3,6,7]
    [1,2,5,6,7]
    true.
    

提交回复
热议问题