[英]Recursive function (maze solver) - can't find a bug;(((
我正在學習javascript,除了諸如遞歸函數之類的東西外,其他一切對我來說都很容易。 我確實了解它們的工作方式,但是在處理示例時,我意識到我無法捕獲導致其無法正常運行的錯誤...
我在下面有一個數組(映射)(0是一個封閉的單元格,1表示路徑已打開),而遞歸函數試圖通過從其左上角的單元格轉到“迷宮”來“查找”路徑右下角的一個。基本上只是使函數“找到”此1s路徑。 但是失敗了;(
var map = [
[1,1,0,0],
[0,1,1,0],
[0,0,1,0],
[0,0,1,1]
]
function findpath(x,y) {
if (x<0 || x>3 || y<0 || y>3) return false; //if it is outside of map
if (x==3 && y==3) return true; // if it is the goal (exit point)
if (map[y][x]==0) return false; //it is not open
map[y][x]=9; //here marking x,y position as part of solution path outlined by "9"
if (findpath(x,y-1) == true) return true;
if (findpath(x+1,y) == true) return true;
if (findpath(x,y+1) == true) return true;
if (findpath(x-1,y) == true) return true;
map[y][x]=8; //unmark x,y as part of solution path outlined by "8"
return false;
};
findpath(0,0);
如果失敗,對“失敗”的描述很少是有用的錯誤報告。
為了有人幫助您,他們需要的不僅是細節。
在這種情況下,導入詳細信息來自JavaScript錯誤控制台。 您應該始終在問題中包含任何錯誤消息。
但是,由於您的代碼很短,因此我可以將其剪切並粘貼到控制台中,並收到以下消息:
RangeError: Maximum call stack size exceeded
這意味着您的函數遞歸過深。 你要么
您需要添加console.log
語句,並觀察代碼在做什么,並查看其為何如此深入。
如果是邏輯錯誤,請修復該邏輯錯誤。 (提示:我可以肯定的是,您永遠不會在地圖上標記出您去過的地方,因此它可以在同一地點自由地來回移動)。
如果不是,那么您需要使用一些更高級的技巧來解決遞歸問題,例如使用生成器函數並將您所做的更改分別存儲在映射中。
快速回答:
因為檢查的順序將其鎖定在一個循環中。
從0:0開始,然后嘗試0:1。 然后從0:1開始-“嗯... 0:0看起來很有希望。讓我們去那里。” 所以回到0:0 ...所以它鎖定了...嘗試最后離開回溯:
if(findpath(x+1,y)) return true;
if(findpath(x,y+1)) return true;
if(findpath(x,y-1)) return true;
if(findpath(x-1,y)) return true;
僅通過交換問題就可以使您擺脫困境。 如果您從3:3開始嘗試達到0:0,您將再次被鎖定。 缺少一種標記已訪問廣場的方法。
我認為您正在嘗試實現a *算法
更新:
這是您的想法起作用。 剛剛添加了您幾乎實施的回溯檢查。
<html>
<head>
</head>
<body>
<script>
var map = [
[1,1,0,0],
[0,1,1,0],
[1,1,1,0],
[1,0,1,1]
]
var goalx = 0;
var goaly = 3;
console.log();
function findpath(x,y) {
// illegal move check
if (x < 0 || x > (map[0].length -1) || y < 0 || y > (map.length - 1)) return false; //if it is outside of map
if (map[y][x]==0) return false; //it is not open
// end move check
if (x== goalx && y== goaly){
console.log('Reached goal at: ' + x + ':' + y);
return true; // if it is the goal (exit point)
}
if(map[y][x] == 9 || map[y][x] == 8)
return false;
console.log('Im here at: ' + x + ':' + y);
map[y][x]=9; //here marking x,y position as part of solution path outlined by "9"
if(findpath(x+1,y))
return true;
if(findpath(x,y+1))
return true;
if(findpath(x,y-1))
return true;
if(findpath(x-1,y))
return true;
map[y][x]=8; //unmark x,y as part of solution path outlined by "8"
return false;
};
findpath(3, 3);
</script>
</body>
</html>
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.