how to visit each point in directed graph

后端 未结 2 909
灰色年华
灰色年华 2020-12-21 18:57

In Prolog, how can I implement graph algorithm in order to find all path in order to implement travel salesman problem in directed graph ?

example :



        
相关标签:
2条回答
  • 2020-12-21 19:17

    I placed some comment that explain what the code does...

    % your directed graph
    edge(x, y).
    edge(y, t).
    edge(t, z).
    edge(y, z).
    edge(x, z).
    
    % get a path from start to end
    path(Start, End, Path) :-
        path(Start, End, [Start], Path).
    
    % when target reached, reverse the visited list
    path(End, End, RPath, Path) :-
        reverse(RPath, Path).
    
    % take non deterministically an edge, check if already visited before use
    path(Start, End, Visited, Path) :-
        edge(Start, Next),
        \+ memberchk(Next, Visited),
        path(Next, End, [Next|Visited], Path).
    

    test:

    ?- path(x,z,P).
    P = [x, y, t, z] ;
    P = [x, y, z] ;
    P = [x, z] ;
    false.
    
    0 讨论(0)
  • 2020-12-21 19:17

    Keep a list of nodes you have already visited. In each step, check if the endpoint of the edge exists in the list or not.

    0 讨论(0)
提交回复
热议问题