【发布时间】:2017-07-04 20:58:52
【问题描述】:
基本上,我的代码需要计算 nxn 矩阵中路径的总和(从 0,0 开始),并将我只能向右或向下移动的最小总和相加。
例如,下面的矩阵应该输出 18,因为最小路径是 5 1 2 4 6,但我不知道我的基本情况应该如何。我知道一旦我到达数组 [n][n] 就应该停止递归。在下面的代码中,我遇到了 stackoverflow 错误。
512 234 566
import java.util.*;
public class shortestpath {
public static int findminpath(int [][]c,int x,int y,int n) {
if (x==n-1 && y==n-1) {
return c[x][y];
} else {
int path1 = findminpath(c,x+1,y,n);
int path2 = findminpath (c,x,y+1,n);
return c[x][y] + Math.min(path1,path2);
}
}
public static void main (String [] args) {
Scanner sc = new Scanner (System.in);
int[][] array = new int[3][3];
for (int i=0; i<array.length; i++){
for (int j=0; j<array.length; j++){
array[i][j] = sc.nextInt();
}
}
System.out.println(findminpath(array,0,0,array.length));
}
}
【问题讨论】:
-
缩进可能看起来像一个肤浅的问题,但它通常是理解某人代码的关键。这里完全失控,根本没有组织。如果你能解决这个问题,你可能离理解问题更近了一步。
-
@tadman 现在好点了吗?
-
这看起来更具可读性。干得好。
标签: java recursion methods stack-overflow