2014-05-16 92 views
2

我試圖找到所有可能的路線,然後打印給用戶,但由於我對prolog很有新意,我遇到了一些麻煩。在圖中查找路線

graph http://i62.tinypic.com/11tu1sh.png

我要打印所有可能的方式去克來自A.這是我到目前爲止有:

direct_path(pathA,pathB). 
direct_path(pathA,pathC). 
direct_path(pathB,pathD). 
direct_path(pathC,pathE). 
direct_path(pathC,pathF). 
direct_path(pathE,pathD). 
direct_path(pathE,pathG). 
direct_path(pathF,pathG). 

upward(X, Y):- direct_path(X, Y). 
upward(X, Z):- direct_path(X, Y), upward(Y, Z). 

這樣我可以檢查是否有可能從A點到G,但我該如何打印這個路徑?

回答

4

只是第三個參數添加到您的upward謂詞來存儲路徑:

upward(X, Y, [X, Y]):- direct_path(X, Y). 
upward(X, Z, [X | Rest]):- direct_path(X, Y), upward(Y, Z, Rest). 

試運行:

?- upward(pathA, pathG, Path). 
Path = [pathA, pathC, pathE, pathG] ; 
Path = [pathA, pathC, pathF, pathG] ; 
false. 

因此,有從A兩條不同的路徑,以G.