【发布时间】:2013-12-09 20:28:18
【问题描述】:
(这不是重复的)我们有一个 2D 迷宫,在所有 4 个面都被 X 包围,并且也有内部块。
迷宫的所有这些字符都存储在二维数组中。程序必须找到从开始'S'到目标'G'的路径。为此,使用名为“solve(int row, int col)”的布尔方法,并使用“S”的行和列索引进行初始化。该算法必须是递归的。如果它能够找到通向“G”的路径,它应该返回 true,否则返回 false。这是我尝试解决这个问题的方法,它显示“部分正确的结果”。
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 处)。它显示 stackOverflow 错误。原因是在这种状态下,递归发生在 2 个点之间(有点像间接递归)。
我该如何解决这个问题。反正有没有告诉程序向上移动而不是向下移动?但是,改变条件语句的位置是行不通的。想想一个有不止一条路要走但只有一条通往“G”的职位。如何回到初始位置并尝试另一条路径?提前致谢。
更新:
Here is a Github Repo link to the complete solution of this problem by me.
【问题讨论】:
标签: java algorithm recursion multidimensional-array maze