A most important observation is for the matrix to be same after row reversals, each single row must be palindromic.

Now to check if a row is palindromic, maintain two pointers, one pointing to start and other to end of row. Start comparing the values present and do start++ and end–. Repeat the process until all elements are checked till the middle of the row. If at each step elements are same, then row is palindromic otherwise not.

If any of the Row is not palindromic then answer is No.

Below is the implementation of the above approach:

C++

filter_none

editclose

play_arrow

linkbrightness_4code

// C++ implementation of the above approach

#include <bits/stdc++.h>

#define ll long long int

usingnamespacestd;

// Function to check Palindromic Condition

voidspecialMatrix(intmatrix[3][3], intN)

{

for(inti = 0; i < N; i++) {

// Pointer to start of row

intstart = 0;

// Pointer to end of row

intend = N - 1;

while(start <= end) {

// Single Mismatch means row is not palindromic

if(matrix[i][start] != matrix[i][end]) {

cout << "No"<< endl;

return;

}

start++;

end--;

}

}

cout << "Yes"<< endl;

return;

}

// Driver Code

intmain()

{

intmatrix[3][3] = { { 1, 2, 1 },

{ 2, 2, 2 },

{ 3, 4, 3 } };

intN = 3;

specialMatrix(matrix, N);

return0;

}

chevron_right

filter_none

Java

filter_none

editclose

play_arrow

linkbrightness_4code

// Java implementation of the above approach

classGFG

{

// Function to check Palindromic Condition

staticvoidspecialMatrix(intmatrix[][], intN)

{

for(inti = 0; i < N; i++)

{

// Pointer to start of row

intstart = 0;

// Pointer to end of row

intend = N - 1;

while(start <= end)

{

// Single Mismatch means

// row is not palindromic

if(matrix[i][start] != matrix[i][end])

{

System.out.println("No");

return;

}

start++;

end--;

}

}

System.out.println("Yes");

return;

}

// Driver Code

publicstaticvoidmain(String[] args)

{

intmatrix[][] = { { 1, 2, 1},

{ 2, 2, 2},

{ 3, 4, 3} };

intN = 3;

specialMatrix(matrix, N);

}

}

/* This code contributed by PrinciRaj1992 */

chevron_right

filter_none

Python3

# Python 3 implementation of the above approach

# Function to check Palindromic Condition
def specialMatrix(matrix, N):
for i in range(N):

If you like GeeksforGeeks and would like to contribute, you can also write an article using contribute.geeksforgeeks.org or mail your article to contribute@geeksforgeeks.org. See your article appearing on the GeeksforGeeks main page and help other Geeks.

Please Improve this article if you find anything incorrect by clicking on the "Improve Article" button below.