因此,我正在尝试查找未加权图的路径及其长度。这是我的代码;您给它一个关系,一个起点和终点以及长度。该代码有效,但是返回的长度比所需的长度短1。
:- use_module(library(lists)).
edge(1,2).
edge(1,4).
edge(1,3).
edge(2,3).
edge(2,5).
edge(3,4).
edge(3,5).
edge(4,5).
connected(X,Y) :-
edge(X,Y)
;
edge(Y,X).
path(Rel,A,B,Path,Len) :-
travel(Rel,A,B,[A],Q,Len),
reverse(Q,Path).
travel(Rel,A,B,P,[B|P],L) :-
call(Rel, A, B), L is 1 .
travel(Rel,A,B,Visited,Path,L) :-
call(Rel,A,C),
C \== B,
\+member(C,Visited),
travel(Rel,C,B,[C|Visited],Path,L1),
L is L1 + 1.
所有这些边的权重/距离均为1,但是给出了诸如
的查询?- path(connected, 1, 5, Path, Length).
返回的每个长度都应少1。
任何有帮助的建议。
答案 0 :(得分:0)
我没有尝试根据经验来修正在谓词travel
中计算路径长度的方式,我知道在处理列表以计算另一个属性时重构Prolog代码并不困难,而且通常会这样做。
因此,这重构了谓词reverse/2
。要重构reverse/2
,我们首先需要reverse/2
的工作代码:
% Reverse using accumulator
rev(List,Rev) :-
rev(List,[],Rev) .
rev([],A,A).
rev([H|T],A,R) :-
rev(T,[H|A],R).
rev/2
?- rev([],L).
L = [].
?- rev([a],L).
L = [a].
?- rev([a,b],L).
L = [b, a].
?- rev([a,b,c],L).
L = [c, b, a].
现在要重构rev/2
来计算长度。
rev_n(List,Rev,N) :-
rev_n(List,[],Rev,N) .
rev_n([],A,A,0).
rev_n([H|T],A,R,N) :-
rev_n(T,[H|A],R,N0),
N is N0 + 1.
rev_n/2
?- rev_n([],L,N).
L = [],
N = 0.
?- rev_n([a],L,N).
L = [a],
N = 1.
?- rev_n([a,b],L,N).
L = [b, a],
N = 2.
?- rev_n([a,b,c],L,N).
L = [c, b, a],
N = 3.
最后,只需修改您的代码以使用rev_n/2
,然后删除计算N的代码中不再需要的部分即可。
path_2(Rel,A,B,Path,Len) :-
travel_2(Rel,A,B,[A],Q),
rev_n(Q,Path,Len).
travel_2(Rel,A,B,P,[B|P]) :-
call(Rel, A, B).
travel_2(Rel,A,B,Visited,Path) :-
call(Rel,A,C),
C \== B,
\+member(C,Visited),
travel_2(Rel,C,B,[C|Visited],Path).
示例:
?- path_2(connected, 1, 5, Path, Length).
Path = [1, 2, 5],
Length = 3 ;
Path = [1, 2, 3, 5],
Length = 4 ;
Path = [1, 2, 3, 4, 5],
Length = 5 ;
Path = [1, 4, 5],
Length = 3 ;
Path = [1, 4, 3, 5],
Length = 4 ;
Path = [1, 4, 3, 2, 5],
Length = 5 ;
Path = [1, 3, 5],
Length = 3 ;
Path = [1, 3, 4, 5],
Length = 4 ;
Path = [1, 3, 2, 5],
Length = 4 ;
false.
一种更实用的方法是仅使用length/2
path_3(Rel,A,B,Path,Len) :-
travel_2(Rel,A,B,[A],Q),
reverse(Q,Path),
length(Path,Len).
?- path_3(connected, 1, 5, Path, Length).
Path = [1, 2, 5],
Length = 3 ;
Path = [1, 2, 3, 5],
Length = 4 ;
Path = [1, 2, 3, 4, 5],
Length = 5 ;
Path = [1, 4, 5],
Length = 3 ;
Path = [1, 4, 3, 5],
Length = 4 ;
Path = [1, 4, 3, 2, 5],
Length = 5 ;
Path = [1, 3, 5],
Length = 3 ;
Path = [1, 3, 4, 5],
Length = 4 ;
Path = [1, 3, 2, 5],
Length = 4 ;
false.