我試圖解決一個陷入回圈的迷宮,但我不明白為什么。我想我可能需要添加一些更多的條件,我已經看過其他人的代碼,但它們看起來太復雜了。
function solve(m, s, x, y) {
if (x == 9 && m[x][y] == "1")
{return;} //if last row, found door
if (m[x 1][y] == "1") { //down
s.push([x 1] ", " [y]);
solve(m, s, x 1, y);
}
if (m[x][y 1] == "1") { //left
s.push([x] ", " [y 1]);
solve(m, s, x, y 1);
}
if (m[x][y-1] == "1") { //right
s.push([x] ", " [y-1]);
solve(m, s, x, y-1);
}
if (matrix[x-1][y] == "1") { //up
s.push([x-1] ", " [y]);
solve(m, s, x-1, y);
}
s.pop(); //if bad path with no end
}
uj5u.com熱心網友回復:
問題是您沒有標記您訪問了哪些單元格,因此您將再次訪問同一個單元格,導致坐標 4,8 和 4,9 之間無休止的來回時刻。
解決這個問題的一種方法是在矩陣中留下一個帶有另一個值的痕跡,比如值 2:
// ...
if (x == 9 && matrix[x][y] == "1") {
{ return; } //if last row, found door
matrix[x][y] = 2; // mark as visited <-- add this
// ...
對您的代碼的一些評論:
將矩陣值與字串進行比較,同時用數值初始化矩陣,這有點奇怪。
你可以避開一些代碼重復,并在細胞和隨后做檢查1
push在開始的功能,而不是做那之前的(遞回)呼叫。
轉載請註明出處,本文鏈接:https://www.uj5u.com/yidong/365884.html
標籤:javascript 算法 矩阵 深度优先搜索 迷宫
