我正在尝试使用网格递归来解决项目Euler(项目16)上的问题,并且它运行得不是很好 - 我只是看起来像一个无限循环。目标是计算从20x20网格的左上角到网格右下角可以采取多少路线,所以我从原点开始并在myGrid [20] [20]中放置一个数字,表明它是在右下角。
private static int[][] myGrid;
public static int numRoutes(int x, int y){
if (x < 0 || x >= 20 || y < 0 || y>= 20){
return 0;
}
if (myGrid[x][y] == 1){
return 1;
}
int count = 0;
count += numRoutes(x+1, y);
count += numRoutes(x, y+1);
return count;
}
public static void main (String args[]) throws Exception{
myGrid = new int[21][21];
for (int i = 0; i < 21; i++){
Arrays.fill(myGrid[i], 0);
}
myGrid[20][20] = 1;
int num = numRoutes(0,0);
System.out.println(num);
}
这包括我的大多数递归,我认为我有所有适当的基本情况。对于出了什么问题的任何想法?
答案 0 :(得分:0)
你的程序不会进入无限循环。它只有很多选项,看起来像......
要测试它,只需将数组大小减小到5X5
....你会发现它结束了......
话虽如此,由于存在错误,您的结果将始终为0
if (x < 0 || x >= 20 || y < 0 || y>= 20){
应该是
if (x < 0 || x > 20 || y < 0 || y > 20){
,而不是...
另外,我不认为这个算法可以为你提供2点之间所有路径的计数...它只是给你所有最短路径的计数...自从流量仅来自top to bottom
和left to right
......不是朝其他方向......