
Given a square matrix referred to as mat, the task is to calculate the sum of its diagonal elements. The sum must include:
For elements where the primary and secondary diagonals intersect, they should only be counted once in the sum to avoid duplication.
Input:
Output:
Explanation:
Input:
Output:
Input:
Output:
n == mat.length == mat[i].length1 <= n <= 1001 <= mat[i][j] <= 100To solve this problem of summing the diagonal elements of a square matrix, we use the following approach:
Iterate through each row index i from 0 to n - 1:
mat[i][i] for the primary diagonal.mat[i][n - 1 - i] for the secondary diagonal.Avoid double-counting the center element (which lies on both diagonals) by:
n is odd (where i == n - 1 - i).This strategy yields a time complexity of O(n) and ensures all required elements are summed without duplication. The implementation is straightforward and efficient for the given constraint limits.
The code provides a solution for calculating the sum of both the primary and secondary diagonals in a square matrix but subtracts the middle element once in the case of odd-dimension matrices, to avoid double-counting. Follow these details to understand the structure of this C++ solution:
sumDiagonals that takes a 2D integer vector (vector<vector<int>>& matrix).size to the number of rows (or columns, as it's square) of the matrix, and total as an accumulator for the sum.index from 0 to size - 1.matrix[index][index] to total.matrix[size - 1 - index][index] to total.size of the matrix is odd, subtract the center element matrix[size / 2][size / 2] once from total to adjust for double counting.total.Ensure the supplied matrix is square to avoid any errors, as the code assumes this when accessing diagonal elements.
0 Comments
Be the first to comment and share your perspective with the community.