Check if Matrix remains unchanged after row reversals in Python

PythonServer Side ProgrammingProgramming

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

686
282
333

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
raja
Published on 19-Jan-2021 04:59:11

Advertisements