calculate the sum of diagonals in a matrix

前端 未结 5 1639
梦如初夏
梦如初夏 2020-12-16 01:45

I need to calculate the sum of two diagonals in a matrix in C++, I already have a solution for that but I must be dumb because I cant understand what it is doing, so I would

5条回答
  •  [愿得一人]
    2020-12-16 02:23

    How about I try to explain this version? :D

    There are 3 important parts of the code:

    • inputing the matrix
    • calculating major diagonal ( \ direction)
    • calculating minor diagonal ( / direction)

    And here they are, explained:

    // input elements
    for(i=1;i<=n;i++) // from left to right
    {
        for(j=1;j<=n;j++) // from up to down
            cin>>a[i][j]; // input element at (i,j) position
    }
    

    Here, d and s contain the inter-values of major and minor diagonal respectively. At the end of 2 loops, they will contain the results

    for (i=1;i<=n;i++)
         for (j=1;j<=n;j++)
         {
            if(i==j)          // major diagonal - if coordinates are the same
               d=d+a[i][j];   // e.g. (1,1), (2,2)
            if(j==n-i+1 || i==n-j+1)  // coordinates of the minor diagonal - check
               s=s+a[i][j];           // e.g. n=3 (3,1) (2,2) ...
          }
    

    Hope this helps.

    Note that this code starts matrix coordinates at 1 instead of 0, so you will actually need to allocate (n+1)x(n+1) space for the matrix:

    double a[n+1][n+1];
    

    before using it.

    Also, the code you gave is not most effective. It has O(n^2) complexity, while the task can be done in O(n) like so:

    // matrix coordinates now start from 0
    for (int i=0; i < n; ++i){
        d += a[i][i]; // major
        s += a[i][n-1-i]; // minor
    }
    

提交回复
热议问题