The Wayback Machine - https://web.archive.org/web/20211007122731/https://www.geeksforgeeks.org/check-if-all-the-diagonals-of-the-matrix-are-palindromic-or-not/
Skip to content
Related Articles

Related Articles

Improve Article

Check if all the diagonals of the Matrix are palindromic or not

  • Last Updated : 07 Oct, 2021

Given a matrix mat[][] of dimensions N*M, the task is to check if all the diagonals of the matrix(from top-right to bottom-left) are palindromic or not. If found to be true, then print Yes. Otherwise, print No.

Examples:

Attention reader! Don’t stop learning now. Get hold of all the important DSA concepts with the DSA Self Paced Course at a student-friendly price and become industry ready.  To complete your preparation from learning a language to DS Algo and many more,  please refer Complete Interview Preparation Course.

In case you wish to attend live classes with experts, please refer DSA Live Classes for Working Professionals and Competitive Programming Live for Students.

Input: mat[][] = [[1, 0, 0, 0], [0, 1, 1, 1], [0, 1, 0, 1], [0, 1, 1, 0]]
Output: Yes
Explanation:
All the diagonals of the matrix mat[][] is given by:

  • {1}
  • {0, 0}
  • {0, 1, 0}
  • {0, 1, 1, 0}
  • {1, 0, 1}
  • {1, 1}
  • {0}

As all the above diagonals are palindromic. Therefore, print Yes.

Input: mat[][] = [[1, 0, 0, 0], [1, 1, 0, 1], [1, 0, 1, 1], [0, 1, 0, 1]]
Output: No

Approach: The given problem can be solved by performing the diagonal traversal of the matrix and for every diagonal traversal check if the elements are palindromic or not. If there exists any such diagonal which is not palindromic, then print Yes. Otherwise, print No.

Below is the implementation of the above approach: 

C++




// C++ program for the above approach
#include <bits/stdc++.h>
using namespace std;
  
#define N 5
  
// Function to check if the matrix is
// palindrome or not
string isbinaryMatrixPalindrome(
    int mat[N][N])
{
  
    // Traverse the matrix and check if
    // top right and bottom left elements
    // have same value
    for (int i = 0; i < N - 1; i++) {
        for (int j = N - 1; j > i; j--) {
  
            // If top right element is not
            // equal to the bottom left
            // element return false
            if (mat[i][j] != mat[j][i]) {
                return "Np";
            }
        }
    }
  
    return "Yes";
}
  
// Driver Code
int main()
{
    int mat[N][N] = { { 1, 0, 0, 1, 1 },
                      { 0, 1, 0, 1, 0 },
                      { 0, 0, 1, 1, 1 },
                      { 1, 1, 1, 0, 1 },
                      { 1, 0, 1, 1, 0 } };
  
    cout << isbinaryMatrixPalindrome(mat);
  
    return 0;
}
Output:
Yes

Time Complexity: O(N2)
Auxiliary Space: O(1)


My Personal Notes arrow_drop_up
Recommended Articles
Page :