Rotate Image
Examples
Example 1:
Input: matrix = [
[1,2],
[3,4]
]
Output: [
[3,1],
[4,2]
]
Example 2:
Input: matrix = [
[1,2,3],
[4,5,6],
[7,8,9]
]
Output: [
[7,4,1],
[8,5,2],
[9,6,3]
]
Example 1:
Input: matrix = [
[1,2],
[3,4]
]
Output: [
[3,1],
[4,2]
]
Example 2:
Input: matrix = [
[1,2,3],
[4,5,6],
[7,8,9]
]
Output: [
[7,4,1],
[8,5,2],
[9,6,3]
]
Given a square n x n matrix of integers matrix, rotate it by 90 degrees clockwise.
You must rotate the matrix in-place. Do not allocate another 2D matrix and do the rotation.
n == matrix.length == matrix[i].length1 <= n <= 20-1000 <= matrix[i][j] <= 1000Rotate the matrix in-place by first transposing it, then reversing each row. Transpose swaps matrix[i][j] with matrix[j][i], and reversing rows completes the 90-degree clockwise rotation.
A 90-degree clockwise rotation maps (i, j) to (j, n - 1 - i). Transposing swaps indices, and reversing each row applies the column reversal, producing exactly this mapping for every cell.
O(n^2)O(1)class Solution:
def rotate(self, matrix: List[List[int]]) -> None:
n = len(matrix)
for i in range(n):
for j in range(i + 1, n):
matrix[i][j], matrix[j][i] = matrix[j][i], matrix[i][j]
for row in matrix:
row.reverse()