Check If Matrix Remains Unchanged After Row Reversals in Python



Suppose we have a square matrix. We have to check whether the matrix remains same after performing row reversal operations on each row, or not.

So, if the input is like

6 8 6
2 8 2
3 3 3

then the output will be True

To solve this, we will follow these steps −

  • n := row count of matrix
  • for i in range 0 to n - 1, do
    • left := 0, right := n - 1
    • while left <= right, do
      • if matrix[i, left] is not same as matrix[i, right], then
        • return False
      • left := left + 1, right := right - 1
  • return True

Example

Let us see the following implementation to get better understanding −

 Live Demo

def solve(matrix):
   n = len(matrix)
   for i in range(n):
      left = 0
      right = n - 1
      while left <= right:
         if matrix[i][left] != matrix[i][right]:
            return False
         left += 1
         right -= 1
   return True
matrix = [
         [6,8,6],
         [2,8,2],
         [3,3,3]]
print(solve(matrix))

Input

[
   [6,8,6],
   [2,8,2],
   [3,3,3]]

Output

True
Updated on: 2021-01-19T05:01:22+05:30

64 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements