Python Program to Rotate Matrix Elements

Python Program to Rotate Matrix Elements

Rotating matrix elements refers to the process of shifting matrix elements in a specific pattern. Here's an example of rotating a matrix in a clockwise manner:

Given a matrix:

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 

After rotating the outermost layer clockwise:

5 1 2 3 9 10 6 4 13 11 7 8 14 15 16 12 

To achieve this rotation in Python, follow these steps:

  1. Use four loops, one for each boundary (top, right, bottom, left).
  2. Store the boundary elements in a temporary list.
  3. Rotate the elements in this list.
  4. Place the rotated elements back to the matrix.

Here's the Python program to rotate matrix elements:

def rotateMatrix(matrix): if not len(matrix): return top = 0 bottom = len(matrix)-1 left = 0 right = len(matrix[0])-1 while left < right and top < bottom: # Store the first row, for future use prev = matrix[top+1][left] # Move elements of top row for i in range(left, right+1): curr = matrix[top][i] matrix[top][i] = prev prev = curr top += 1 # Move elements of rightmost column for i in range(top, bottom+1): curr = matrix[i][right] matrix[i][right] = prev prev = curr right -= 1 # Move elements of bottom row for i in range(right, left-1, -1): curr = matrix[bottom][i] matrix[bottom][i] = prev prev = curr bottom -= 1 # Move elements of leftmost column for i in range(bottom, top-1, -1): curr = matrix[i][left] matrix[i][left] = prev prev = curr left += 1 return matrix # Test mat = [ [1, 2, 3, 4], [5, 6, 7, 8], [9, 10, 11, 12], [13, 14, 15, 16] ] rotated_mat = rotateMatrix(mat) for row in rotated_mat: print(row) 

This program will output the rotated matrix as described in the example above.


More Tags

highest python-3.7 maven-ant-tasks kramdown owin admin evaluation connection-pooling responsive-design matplotlib-animation

More Programming Guides

Other Guides

More Programming Examples