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

时间:2016-01-26 09:37:26

标签: c# matrix

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

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 个答案:

答案 0 :(得分:6)

无需扫描完整矩阵

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];