(這不是重複的)我們在所有4邊都有一個由X包圍的2D迷宮,並且也有內部塊。
迷宮中的所有這些字符都存儲在二維數組中。程序必須找到從開始'S'到目標'G'的路徑。爲此,一個名爲'solve(int row,int col)的布爾方法被使用並且用'S'的行和列索引進行初始化。該算法必須是遞歸的。它應該返回true,如果它能夠找到'G'的路徑並且其他方式是錯誤的。以下是我試圖解決這個顯示「部分正確結果」的問題。二維迷宮的遞歸算法?
public boolean solve(int row, int col) {
char right = this.theMaze[row][col + 1];
char left = this.theMaze[row][col - 1];
char up = this.theMaze[row - 1][col];
char down = this.theMaze[row + 1][col];
if (right == 'G' || left == 'G' || up == 'G' || down == 'G') {
return true;
}
System.out.println("position=>"+"("+row + ":" + col+")");
if (right == ' ') {
return solve(row,col+1);
}
if (down == ' ') {
return solve(row+1,col);
}
if (left == ' ') {
return solve(row,col-1);
}
if (up == ' ') {
return solve(row-1,col);
}
return false;
}
這裏是它解決了輸出:
0 1 2 3 4 5 6 7 8 9 10
0 X X X X X X X X X X X
1 X X S X X X X X X X
2 X X X X X X X X X
3 X X X X X X X X X
4 X X X X X X X X X
5 X X X X X X X X X
6 X X X X X X X X X
7 X X X X X X X G X X
8 X X X X
9 X X X X X X X X X X X
position=>(1:2)
position=>(2:2)
position=>(3:2)
position=>(4:2)
position=>(5:2)
position=>(6:2)
position=>(7:2)
position=>(8:2)
position=>(8:3)
position=>(8:4)
position=>(8:5)
position=>(8:6)
position=>(8:7)
true
但是,當我把 'G' 一步向上(在6,8)。它顯示堆棧溢出錯誤。原因是因爲遞歸發生在這個狀態的2個點之間(不知怎的,就像間接遞歸一樣)。
我該如何解決這個問題。無論如何要讓程序向上移動而不是向下移動?改變條件語句的位置不會工作。並且認爲一個有多條路徑但只有一條導致'G'的位置。如何回到初始位置並嘗試另一條路徑?提前致謝。
更新:
Here is a Github Repo link to the complete solution of this problem by me.
我會嘗試,看看它是否工作。 –
絕對,它現在工作! –