Advertisement
coffeebeforecode

How to rotate a matrix by one element anti clockwise- using python

Jan 21st, 2021
507
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Python 1.64 KB | None | 0 0
  1. # Function to rotate a matrix anticlockwise
  2. # Modified code from https://www.geeksforgeeks.org/rotate-matrix-elements/
  3. # Question :
  4. # https://stackoverflow.com/questions/37839572/how-to-rotate-a-matrix-by-one-element-anti-clockwise-n-times-using-c-or-in-pyt
  5. # By Devansh Sehgal
  6. def rotMatrixAntiClock(mat):
  7.  
  8.     if not len(mat):
  9.         return
  10.  
  11.     """
  12.        top : starting row index
  13.        bottom : ending row index
  14.        left : starting column index
  15.        right : ending column index
  16.    """
  17.  
  18.     top = 0
  19.     bottom = len(mat)-1
  20.  
  21.     left = 0
  22.     right = len(mat[0])-1
  23.  
  24.     while left < right and top < bottom:
  25.  
  26.         # Store the first element of next row,
  27.         # this element will replace first element of
  28.         # current row
  29.         prev = mat[top+1][right]
  30.         # Move elements of top row one step left
  31.         for i in range(right,left-1,-1):
  32.             curr = mat[top][i]
  33.             mat[top][i] = prev
  34.             prev = curr
  35.  
  36.         top += 1
  37.  
  38.         # Move elements of leftmost column one step downwards
  39.         for i in range(top, bottom+1):
  40.             curr = mat[i][left]
  41.             mat[i][left] = prev
  42.             prev = curr
  43.  
  44.         left += 1
  45.  
  46.         # Move elements of bottom row one step right
  47.         for i in range(left,right+1):
  48.             curr = mat[bottom][i]
  49.             mat[bottom][i] = prev
  50.             prev = curr
  51.  
  52.         bottom -= 1
  53.  
  54.         # Move elements of rightmost column one step upwards
  55.         for i in range(bottom, top-1, -1):
  56.             curr = mat[i][right]
  57.             mat[i][right] = prev
  58.             prev = curr
  59.  
  60.         right -= 1
  61.  
  62.     return mat
  63.  
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement