Algorithm Steps
- Given an
n x n
square matrix. - Step 1: Transpose the matrix: swap
matrix[i][j]
withmatrix[j][i]
for alli < j
. - Step 2: Reverse each row of the matrix.
- The matrix is now rotated 90 degrees clockwise.
Rotate a Matrix 90 Degrees Clockwise (In-place) Code
Python
JavaScript
Java
C++
C
def rotate_matrix(matrix):
n = len(matrix)
# Transpose the 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]
# Reverse each row
for row in matrix:
row.reverse()
return matrix
# Sample Input
mat = [
[1, 2, 3],
[4, 5, 6],
[7, 8, 9]
]
rotated = rotate_matrix(mat)
for row in rotated:
print(row)