Matrix diagonal sum problem in C# and explain

The matrix diagonal sum problem involves calculating the sum of the elements on the main diagonal and the anti-diagonal of a square matrix.

Problem Statement

Given a square matrix (n x n), find the sum of the elements on its main diagonal and the anti-diagonal. The main diagonal consists of elements from the top-left to the bottom-right, and the anti-diagonal consists of elements from the top-right to the bottom-left.

Example

For the matrix:

[
 [1, 2, 3],
 [4, 5, 6],
 [7, 8, 9]
]
  • Main diagonal: 1, 5, 9 (sum = 15)
  • Anti-diagonal: 3, 5, 7 (sum = 15)

The total sum would be 15 + 15 = 30. However, if the matrix size is odd, the center element (in this case, 5) is counted twice. Therefore, we subtract it once from the total.

C# Implementation

Here’s how to implement this in C#:

using System;

public class MatrixDiagonalSum
{
    public static int DiagonalSum(int[][] matrix)
    {
        int n = matrix.Length;
        int sum = 0;

        for (int i = 0; i < n; i++)
        {
            sum += matrix[i][i];                // Main diagonal
            sum += matrix[i][n - 1 - i];       // Anti-diagonal
        }

        // If the matrix size is odd, subtract the middle element
        if (n % 2 == 1)
        {
            sum -= matrix[n / 2][n / 2];
        }

        return sum;
    }

    public static void Main(string[] args)
    {
        int[][] matrix = new int[][]
        {
            new int[] { 1, 2, 3 },
            new int[] { 4, 5, 6 },
            new int[] { 7, 8, 9 }
        };

        int result = DiagonalSum(matrix);
        Console.WriteLine($"The sum of the diagonals is: {result}");
    }
}

Explanation

  1. Data Structure:

    • The matrix is represented as a jagged array (int[][]), where each inner array corresponds to a row in the matrix.
  2. DiagonalSum Method:

    • The method takes the matrix as input and calculates the sum of the diagonals.
    • It uses a single loop that runs from 0 to n-1 (where n is the size of the matrix):
      • It adds the element at (i, i) (main diagonal).
      • It adds the element at (i, n - 1 - i) (anti-diagonal).
    • After the loop, if the matrix has an odd size, it subtracts the middle element (which was added twice) by accessing matrix[n / 2][n / 2].
  3. Main Method:

    • It initializes a sample square matrix and calls the DiagonalSum method.
    • Finally, it prints the sum of the diagonals.

Complexity

  • Time Complexity: O(n), where n is the number of rows (or columns) of the matrix, as we loop through the elements once.
  • Space Complexity: O(1) since we are using a constant amount of additional space.

Output

When you run the program, it will display:

The sum of the diagonals is: 30

This implementation efficiently calculates the sum of the main and anti-diagonals of a square matrix, handling odd-sized matrices appropriately.