Given an n x n integer matrix matrix and an integer turns, perform turns clockwise rotations of the matrix, with one exception: every cell on either the main diagonal or the anti-diagonal must remain in its original position.
A cell at zero-based row r and column c is fixed exactly when r == c or r + c == n - 1. When n is odd, the center cell lies on both diagonals and is still fixed only once. During one rotation, each non-fixed value at (r, c) is placed at (c, n - 1 - r), the same destination it would have in a full clockwise turn. Fixed cells do not move.
Equivalently, the two diagonals divide the remaining cells into four triangular regions: top, right, bottom, and left. One rotation moves the top region to the right, the right to the bottom, the bottom to the left, and the left to the top. Return the grid after exactly turns rotations.
Implement rotate_except_diagonals(matrix: list[list[int]], turns: int) -> list[list[int]].
Example 1:
Input: matrix = [[5,1,6],[2,9,3],[7,4,8]], turns = 1
Output: [[5,2,6],[4,9,1],[7,3,8]]
Explanation: The diagonal values 5, 6, 9, 8, 7 stay fixed. The off-diagonal values rotate: 1 moves to (1,2), 3 moves to (2,1), 4 moves to (1,0), and 2 moves to (0,1).
matrix = [[5,1, 6], [2, 9, 3], [7, 4, 8]] turns = 1
[[5,2, 6], [4, 9, 1], [7, 3, 8]]
| 0 | 1 | 2 | |
|---|---|---|---|
| 0 | 5 | 1 | 6 |
| 1 | 2 | 9 | 3 |
| 2 | 7 | 4 | 8 |
Input 3x3 matrix; turns = 1 clockwise rotation, but diagonal cells must stay put.
Example 2:
Input: matrix = [[10,20,30,40],[50,60,70,80],[90,100,110,120],[130,140,150,160]], turns = 1
Output: [[10,50,90,40],[140,60,70,20],[150,100,110,30],[130,120,80,160]]
Explanation: For an even-sized grid, the two diagonals are disjoint, so eight diagonal values remain fixed while the other eight positions rotate.
Example 3:
Input: matrix = [[3,8],[2,7]], turns = 3
Output: [[3,8],[2,7]]
Explanation: With n = 2, every position lies on a diagonal, so the matrix is unchanged for any number of turns.
Constraints:
n rows and n columns.matrix = [[5,1, 6], [2, 9, 3], [7, 4, 8]] turns = 1
[[5,2, 6], [4, 9, 1], [7, 3, 8]]
| 0 | 1 | 2 | |
|---|---|---|---|
| 0 | 5 | 1 | 6 |
| 1 | 2 | 9 | 3 |
| 2 | 7 | 4 | 8 |
Input 3x3 matrix; turns = 1 clockwise rotation, but diagonal cells must stay put.