VOOZH about

URL: https://www.geeksforgeeks.org/dsa/program-check-diagonal-matrix-scalar-matrix/

⇱ Program to check diagonal matrix and scalar matrix - GeeksforGeeks


  • Courses
  • Tutorials
  • Interview Prep

Program to check diagonal matrix and scalar matrix

Last Updated : 21 Dec, 2024

Given a square matrix mat[][] of order n*n, the task is to check if it is a Diagonal Matrix and Scalar matrix.

Diagonal Matrix: A square matrix is said to be a diagonal matrix if the elements of the matrix except the maindiagonal are zero. A square null matrix is also a diagonal matrix whose maindiagonal elements are zero

Examples:

Input: mat[][] = [[4, 0, 0, 0],
[0, 5, 0, 0],
[0, 0, 2, 0],
[0, 0, 0, 1]]

Output: True
Explanation: Main Diagonal = [4, 5, 2, 1], all the elements except main diagonal are zero.

Input: mat[][] = [[6, 10, 12, 0],
[0, 5, 0, 0],
[0, 0, 9, 0],
[0, 0, 0, 1]]

Output: False
Explanation: Main Diagonal = [6, 5, 9, 1], all the elements except main diagonal are not zero.

Approach:

The row and column indexes of Primary or Major diagonal are same i.e. lets say mat[][] is matrix then mat[i][i] will be a Major Diagonal element. The idea is to traverse the matrix and check if all elements except main diagonal are zero.


Output
True

Time Complexity: O(n2), where n represents the number of rows and columns of the given matrix.
Auxiliary Space: O(1), no extra space is required.

Scalar Matrix: A square matrix is said to be a scalar matrix if all the maindiagonal elements are equal and other elements are zero. The scalar matrix can also be written in form of n * I, where n is any real number and I is the Identity Matrix

Examples: 

Input: mat[][] = [[4, 0, 0, 0],
[0, 4, 0, 0],
[0, 0, 4, 0],
[0, 0, 0, 4]]

Output: True
Explanation: Main Diagonal = [4, 4, 4, 4] diagonal elements are equal and other elements are zero.

Input: mat[][] = [[4, 0, 0, 0],
[0, 4, 0, 0],
[0, 0, 1, 0],
[0, 0, 0, 4]]

Output: False
Explanation: Main Diagonal = [4, 4, 1, 4], diagonal elements are not equal.

Approach:

The row and column indexes of Primary or Major diagonal are same i.e. lets say mat[][] is matrix then mat[i][i] will be a Major Diagonal element. The idea is to traverse the matrix and check if all elements of main diagonal are equal and other elements are zero.


Output
True

Time Complexity: O(n2), where n represents the number of rows and columns of the given matrix.
Auxiliary Space: O(1)

Comment
Article Tags: