public static void main(String[] args) {
// TODO Auto-generated method stub
int matriz[][]= {{1,2,3,4,5},{1,2,3,4,55}};
System.out.println(sumMatriz(matriz, 0, 0));
}
public static int sumMatriz(int [][]matriz, int i, int j) {
if(i>=matriz.length-1 && j>=matriz[i].length-1) {
return matriz[i][j];
}else {
if(j>=matriz[i].length-1) {
if(matriz[i][j]%2==0) {
return matriz[i][j]+sumMatriz(matriz, i+1, 0);
}else {
return sumMatriz(matriz, i+1, 0);
}
}else {
if(matriz[i][j]%2==0) {
return matriz[i][j]+sumMatriz(matriz, i, j+1);
}else {
return sumMatriz(matriz, i, j+1);
}
}
}
}
output
67
如果我在return 0;
内放置return matriz[i][j];
而不是if(i>=matriz.length-1 && j>=matriz[i].length-1) {
,则不要识别矩阵的最后一个元素并将其他元素相加。如果将return matriz[i][j];
加上所有对数,则包括最后一个元素(损害数)。
不知道会发生什么 感谢
答案 0 :(得分:0)
您可以按如下方式重写sumMatriz
:
// I'm moving in the j direction till I can't go any further
// in that row then I reset j and increase i (go to the next row)
// till I can't go any further
// Think of the recursive equivalent
// for(int i = 0; i < matriz.length; ++i) {
// for(int j = 0; j < matriz[i].length; ++j) {
// ... do stuff ...
// }
// }
public static int sumMatriz(int [][]matriz, int i, int j) {
// We have reached the maximum row index i so
// we are done adding
if(i >= matriz.length) {
return 0;
}
// We have reached the maximum column index j for this row
// jump to the next row and continue searching
if(j >= matriz[i].length) {
return sumMatriz(matriz, i + 1, 0);
}
if(matriz[i][j] % 2 == 0) {
// The number is even so add it
return matriz[i][j] + sumMatriz(matriz, i, j + 1);
} else {
// increase the column index j and continue
return sumMatriz(matriz, i, j + 1);
}
}
public static void main(String[] args) {
int matriz[][] = {{1,2,3,4,5},{1,2,3,4,55}};
System.out.println(sumMatriz(matriz, 0, 0));
// outputs 12
}
答案 1 :(得分:0)
不确定你的练习的目的是否是递归地写这个(如果是这种情况请忽略我的答案)但是如果目的是总结你的多维矩阵我会写得有点不同,如下所示:
public static void main(String[] args) {
Integer matriz[][]= {{1,2,3,4,5},{1,2,3,4,55}};
System.out.println(sumMatrix(matriz));
}
private static Integer sumMatrix(Integer matrix[][]) {
return Arrays.asList(matrix)
.stream()
.flatMap(i -> Arrays.asList(i).stream())
.filter(i -> i % 2 == 0)
.collect(Collectors.summingInt(i -> i));
}