我编写了一个简短的Java代码,用于解决从S到G的简单迷宫问题。
我不明白问题出在哪里。
import java.util.Scanner;
public class tester
{
static char [][] grid={
{'.','.'},
{'.','.'},
{'S','G'},
};
static int a=2;
static int b=2;
static boolean findpath(int x, int y)
{
if((x > grid.length-1) || (y > grid[0].length-1) || (x < 0 || y < 0))
{
return false;
}
else if(x==a && y==b){
return true;
}
else if (findpath(x,y-1) == true){
return true;
}
else if (findpath(x+1,y) == true){
return true;
}
else if (findpath(x,y+1) == true) {
return true;
}
else if (findpath(x-1,y) == true){
return true;
}
return false;
}
public static void main(String[] args){
boolean result=findpath(2,0);
System.out.print(result);
}
}
我直接给出了起始位置,目标定义在&amp;湾帮忙。
答案 0 :(得分:1)
没有像(2; 2)那样的细胞。数组从0开始编号。您还会获得不定式递归,因为您多次访问一个单元格。
答案 1 :(得分:0)
无论这个神秘算法试图实现什么,y
参数设置为2的函数将立即返回false grid[0].length-1==1
并且条件y > grid[0].length-1
为真。所以if(x==a && y==b){
永远不会成真。