计算矩阵对角线上的数字之和

4

我有一个动态矩阵,需要按以下方式计算数字的总和:

0 1 2 3 4 5 6

10 11 12 13 14 15 16

20 21 22 23 24 25 26

30 31 32 33 34 35 36

40 41 42 43 44 45 46

50 51 52 53 54 55 56

60 61 62 63 64 65 66

我不知道应该如何比较ij

long result = 0;
for (int i = 0; i < len; i++)
{
    for (int j = 0; j < len; j++)
    {
        // only works for diagonal
        if (i == j) // should use j - 1 or i - 1? 
        {
            result += matrix[i][j];
        }
    }
}
1个回答

7
不需要扫描整个矩阵:
long result = 0;
for (int i = 0; i < len; i++)
{
     result += matrix[i][i];      // diagonal
     if (i < len - 1)             // stay within array bounds
        result += matrix[i][i+1]; // next to diagonal
}

没有进行每次迭代的索引检查的修改:
// assign corner value from bottom row to result
long result = matrix[len-1][len-1];
// for each row (except last!) add diagonal and next to diagonal values
for (int i = 0; i < len-1; i++)    
     result += matrix[i][i] + matrix[i][i+1];

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接