給定圖序言,找到一個圖的鄰居
G = [1 - 5, 2 - 4, 2 - 6, 3 - 4, 3 - 6, 3 - 9, 4 - 7, 5 - 7, 6 - 7, 6 - 8, 6 - 9]
我必須找到每一個節點的所有鄰居,並創建一個列表這種形式
Graph = [(1, [5]), (2, [4, 6]), (3, [4, 6, 9]), (4, [2, 3, 7]), (5, [1, 7]), (6, [2, 3, 7, 8, 9]), (7, [4, 5, 6]), (8, [6]), (9, [3, 6])].
這裏是我的方法:
search_for_neighbors(Ne,V,Ne,V).
search_for_neighbors(V,V,Ne,Ne).
search_for_neighbors(_,_,_,0).
neigh(_,[],_).
neigh(N,[(V - Ne)|T],Graph) :-
neigh(N,T,Graph1),
search_for_neighbors(N,V,Ne,Result),
add_first(Result,Graph1,Graph).
allneigh(0,_,_).
allneigh(N,G,L) :-
N1 is N - 1,
allneigh(N1,G,L1),
neigh(N,G,L2),
add_last((N,L2),L1,L).
add_first(0, L, L).
add_first(X, L, [X|L]).
add_last(X, [], [X]).
add_last(X, [Y|L1], [Y|L2]):- add_last(X,L1,L2).
我運行我的Prolog代碼:
?- allneigh(9,[1 - 5, 2 - 4, 2 - 6, 3 - 4, 3 - 6, 3 - 9, 4 - 7, 5 - 7, 6 - 7, 6 - 8, 6 - 9],G).
這是我的結果,
G = [(1, [5|_464]), (2, [4, 6|_508]), (3, [4, 6, 9|_556]), (4, [2, 3, 7|_606]), (5, [1, 7|_658]), (6, [2, 3, 7, 8, 9|_712]), (7, [4, 5, 6|_769]), (8, [6|_827]), (9, [3, 6|_883])]
爲什麼我有這樣的行爲?