2014-11-20 116 views
1

假設我們有一個棋盤上的機器人,可以像國王一樣移動。序言:在迷宮中尋找路徑

董事會與從[1,1]到[8,8]的座標。

起始位置是[1,1]最後是[8,8]。列表X包含障礙物座標列表[[1,4],[2,5],[5,6]]。問題是:機器人是否有可能從起始位置移動到最終位置。

我做了這個謂詞:

path([A,B],_):- A is 8, B is 8. 
path([A,B],X):- 
     possibleMoves(A,B,L), % possibleMoves returns a list of all the possible coords that 
     the robot can go to. (Example for [1,1] are [[0,1],[0,0],[2,1]...]) 

     member([Ex,Ey],L), % member generates all the possible members from the list L 
     not(member([Ex,Ey],X)), % if this member is not member of the "forbidden ones" 
     Ex<9,Ex>0,Ey<9,Ey>0, % and its coords are on the board 
     path([Ex,Ey],X). 


isTherePath(X):- possibleMoves(1,1,L), 
       member(E,L), 
       path(E,X). 

但有一個錯誤,它不返回任何值。遞歸永不止步我找不到原因。

+1

第一行的意圖是什麼?它將始終將8分配給A和B.我想你想要比較而不是分配。 – 2014-11-20 20:32:51

回答

2

在一個謂詞中定義一個有效的步驟 - 包括所有的限制。堅持這個命名約定:X0「第一」值,X「最後」值

step(Forbidden,[X0,Y0],[X,Y]) :- 
    possibleMoves(X0,Y0,L), % rather: possibleMove([X0,Y0],L), 
    member([X,Y],L), 
    between(1,8,X), 
    between(1,8,Y), 
    non_member([X,Y],Forbidden). 

現在你有一個路徑:

..., closure0(step(Forbidden), S0,S), ... 

closure0/3需要週期的照顧。

+1

謝謝,但我不能使用閉包我必須做出我自己的謂詞。 難道我不能做一個判斷'步驟'來檢查我目前的座標是否是最終的座標。如果我不是,我會使用你定義的這一步。 – chnging 2014-11-20 22:24:21

+1

然後用第一個參數重命名爲step(Forbidden)... – false 2014-11-20 22:28:55