Answer to Question #211832 in Python for sudheer

Question #211832

def rotateMatrix(mat):

   if not len(mat):

    return

  top = 0

  bottom = len(mat)-1

   left = 0

  right = len(mat[0])-1

  while left < right and top < bottom:

    prev = mat[top+1][left]

    for i in range(left, right+1):

      curr = mat[top][i]

      mat[top][i] = prev

      prev = curr

     top += 1

     for i in range(top, bottom+1):

      curr = mat[i][right]

      mat[i][right] = prev

      prev = curr

     right -= 1

  output:[13, 9, 5, 1]

[14, 7, 11, 2,]

[15, 6, 10, 3]

[16 ,12, 8, 4]

output should be like this:

13, 9, 5, 1

14, 7, 11, 2

15, 6, 10, 2

16, 12, 8,


1
Expert's answer
2021-06-30T11:55:40-0400
def rotateMatrix(mat): 
  
    if not len(mat): 
        return
      
   
  
    top = 0
    bottom = len(mat)-1
  
    left = 0
    right = len(mat[0])-1
  
    while left < right and top < bottom: 
  
        prev = mat[top+1][left] 
  
       
        for i in range(left, right+1): 
            curr = mat[top][i] 
            mat[top][i] = prev 
            prev = curr 
  
        top += 1
  
        
        for i in range(top, bottom+1): 
            curr = mat[i][right] 
            mat[i][right] = prev 
            prev = curr 
  
        right -= 1
  
        
        for i in range(right, left-1, -1): 
            curr = mat[bottom][i] 
            mat[bottom][i] = prev 
            prev = curr 
  
        bottom -= 1
  
        
        for i in range(bottom, top-1, -1): 
            curr = mat[i][left] 
            mat[i][left] = prev 
            prev = curr 
  
        left += 1
  
    return mat 
  


def printMatrix(mat): 
    for row in mat:
        print(row) 
  
  

Need a fast expert's response?

Submit order

and get a quick answer at the best price

for any assignment or question with DETAILED EXPLANATIONS!

Comments

No comments. Be the first!

Leave a comment

LATEST TUTORIALS
New on Blog
APPROVED BY CLIENTS