如何找到二维矩阵中对角线的总和?

How can I find the sum of a diagonal in a 2D Matrix?

我是 java 的新手。如何在二维矩阵中找到对角线之和(看起来像 /)?

假设矩阵看起来像这样:

4 6 7
2 4 7 
5 2 7

对角线(看起来像 \)的和是 15 (4+4+7)。 这是我的对角线代码:

public static int Diagonal(int m[][]) { 
    int sum = 0;
    for(int row = 0; row < m[0].length; row++) {
        sum += m[row][row];
    }
    return sum; 
}   

如何找到另一条看起来像 (/) 的对角线的总和?

您可以使用此代码

public static int Diagonal2(int m[][]) {   
    int sum=0;
    for(int row = 0; row < m[0].length; row++) {
        sum += m[row][m.length - row - 1];
    }
    return sum; 
}

喜欢

public class Main {
    public static void main(String[] args) {
        int[][] matrix = { { 4, 6, 7 }, { 2, 4, 7 }, { 5, 2, 7 } };
        StringBuilder sb = new StringBuilder();
        int sum = sumDiagonal(matrix, sb);
        sb.deleteCharAt(sb.length() - 1);
        System.out.println("The sum of the diagonal is " + sum + " (" + sb + ")");
    }

    public static int sumDiagonal(int m[][], StringBuilder sb) {
        int sum = 0;
        for (int row = 0; row < m[0].length; row++) {
            sum += m[row][m[0].length - row - 1];
            sb.append(m[row][m[0].length - row - 1] + "+");
        }
        return sum;
    }
}

输出

The sum of the diagonal is 16 (7+4+5)