fork download
  1. :- set_prolog_flag(verbose,silent).
  2. :- prompt(_, '').
  3. :- use_module(library(readutil)).
  4.  
  5. % 通路の定義
  6. link(a,b).
  7. link(a,c).
  8. link(b,d).
  9. link(c,e).
  10. link(d,f).
  11. link(f,g).
  12. link(f,h).
  13. link(h,g).
  14.  
  15. path(X,Y) :- link(X,Y)|link(Y,X). % 通路を一方通行にしない。この行を削除すると、一方通行になる。
  16.  
  17. % 目的地に着いている場合
  18. pathFind(Pos,Pos,_,[Pos]) :- !. % 目的地から先の探索を中断
  19.  
  20. % 目的地に着いていない場合
  21. pathFind(Pos,Goal,Check,[Pos|Tail]) :-
  22. not(member(Pos,Check)), % 通過地点記録 Check に Pos が含まれないことを確認
  23. path(Pos,Z), % Posと接続したZを見つける
  24. pathFind(Z,Goal,[Pos|Check],Tail). % ZからGoalを目指す。Pos を Check に加える
  25.  
  26. % 全ての経路を探索
  27. pathFindAll(Start,Goal) :- pathFind(Start,Goal,[],Path),print(Path),nl,fail.
  28. pathFindAll(_,_).
  29.  
  30. % 探索の指示の例
  31. :- pathFindAll( a , g ).
  32.  
  33. :- halt.
Success #stdin #stdout 0.02s 32280KB
stdin
Standard input is empty
stdout
[a,b,d,f,g]
[a,b,d,f,h,g]