Python Program to Rotate all Matrix elements except the diagonal K times by 90 degrees in clockwise direction

Python Program to Rotate all Matrix elements except the diagonal K times by 90 degrees in clockwise direction

Rotating a matrix 90 degrees in the clockwise direction while keeping the diagonal elements unchanged requires some careful logic. Here's a step-by-step solution:

  1. Extract all non-diagonal elements into a linear list.
  2. Rotate the list elements to the right by K * (number of elements to move in one 90-degree rotation).
  3. Place the rotated elements back to their corresponding positions.

Here's the Python code to accomplish this:

def rotate_matrix(mat, K): n = len(mat) elements = [] # Extract non-diagonal elements into the list for i in range(n): for j in range(n): if i != j: elements.append(mat[i][j]) # Rotate the list num_rotations = K * (n - 1) elements = elements[-num_rotations:] + elements[:-num_rotations] # Put the rotated elements back into the matrix idx = 0 for i in range(n): for j in range(n): if i != j: mat[i][j] = elements[idx] idx += 1 return mat # Test mat = [ [1, 2, 3], [4, 5, 6], [7, 8, 9] ] K = 1 print(rotate_matrix(mat, K)) 

Note: This program rotates the entire matrix K times by 90 degrees in a clockwise direction, excluding the diagonal elements. Adjust the value of K in the test section to rotate multiple times.


More Tags

distutils pdfminer git-commit rvm service google-translation-api matplotlib-basemap google-sheets-macros flask formarray

More Programming Guides

Other Guides

More Programming Examples