title: Prolog - Find path and its distance between nodes in a graph with passing through all the nodes
body: <p>I am kind of new to prolog and I quite don't understand why this code doesn't work, so I want to find a path and its distance with passing through all the nodes just one time and then returning to the first node here is what I did:</p>
  
  <pre><code>distance(a,b,5).
  distance(b,a,5).
  distance(a,c,3).
  distance(c,a,3).
  distance(c,b,2).
  distance(b,c,2).
  
  
  head([H|List],H).
  tail([H|List],List).
  %Finding the Cycle
    cycle(Node,Cycle) :-
        distance(Node,Next,D),
        cycle(Node,Next,[Node],Cycle).
  
    cycle(Curr,Curr,Visited,Cycle) :-
        reverse([Curr|Visited],Cycle).
    cycle(Node,Curr,Visited,Cycle) :-
        \+ member(Curr,Visited),
        distance(Curr,Next,D),
        cycle(Node,Next,[Curr|Visited],Cycle).
  
      %Finding all the possible paths
      find(Start,Cycle):-findall(Z,cycle(Start,Z),Cycle).
  
      %Selecting only the cycles that contains all the nodes
      path(Start,Cycle,DT):-find(Start,List),
                          path(Start,Cycle,DT,List).
      path(Start,Cycle,DT,List):-head(List,Cycle),
                              tail(List,T),
                              distanceC(Cycle,DT),
                              pathL(Cycle),
                              path(Start,Cycle,DT,T).
  %Calculating the distance of a path
  distanceC([_],0).
  distanceC([X,Y|Rest],DT):-distance(X,Y,D1),distanceC([Y|Rest],DT1), DT is D1 + DT1.
  pathL(H):-      length(H,Z),
                  Z==3.
  </code></pre>
  
  <p><code>path(Start,Cycle,DT,List)</code> doesn't work when I start the Recursion </p>