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

问题描述 投票:0回答:2

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

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

我不明白应该以哪种方式比较

i
j
:

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];
        }
    }
}
c# matrix
2个回答
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];

0
投票
    int d1=0;
    int d2=0;
    int arrLength=arr.Count();
    for(int row=0;row<arrLength;row++){
                d1 += arr[row][row];
                d2 +=arr[row][arrLength-row-1];
            }
© www.soinside.com 2019 - 2024. All rights reserved.