Today we are going to share a Python program to rotate a matrix. If you are a python beginner and want to start learning the python programming, then keep your close attention in this tutorial as I am going to share a Python program to rotate a matrix with the output.
To increase your Python knowledge, practice all Python programs, here is a collection of 100+ Python problems with solutions.
Copy the below python program and execute it with the help of python compiler.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 |
def rotateMatrix(mat): if not len(mat): return """ top : starting row index bottom : ending row index left : starting column index right : ending column index """ top = 0 bottom = len(mat)-1 left = 0 right = len(mat[0])-1 while left < right and top < bottom: # Store the first element of next row, # this element will replace first element of # current row prev = mat[top+1][left] # Move elements of top row one step right for i in range(left, right+1): curr = mat[top][i] mat[top][i] = prev prev = curr top += 1 # Move elements of rightmost column one step downwards for i in range(top, bottom+1): curr = mat[i][right] mat[i][right] = prev prev = curr right -= 1 # Move elements of bottom row one step left for i in range(right, left-1, -1): curr = mat[bottom][i] mat[bottom][i] = prev prev = curr bottom -= 1 # Move elements of leftmost column one step upwards for i in range(bottom, top-1, -1): curr = mat[i][left] mat[i][left] = prev prev = curr left += 1 return mat # Utility Function def printMatrix(mat): for row in mat: print row # Test case 1 matrix =[ [1, 2, 3, 4 ], [5, 6, 7, 8 ], [9, 10, 11, 12 ], [13, 14, 15, 16 ] ] # Test case 2 """ matrix =[ [1, 2, 3], [4, 5, 6], [7, 8, 9] ] """ matrix = rotateMatrix(matrix) # Print modified matrix printMatrix(matrix) |
Output:
5 1 2 3
9 10 6 4
13 11 7 8
14 15 16 12
If you like FreeWebMentor and you would like to contribute, you can write an article and mail your article to [email protected] Your article will appear on the FreeWebMentor main page and help other developers.