Problem: Rotate a Matrix 90 Degrees Clockwise
You are given a square 2D matrix representing an image. Your task is to rotate the image 90 degrees clockwise in place. This means that you should modify the matrix directly, without allocating additional space for another matrix.
Requirements:
-
Transpose the matrix:
- Swap rows and columns. The element at position
matrix[i][j]
should be swapped with the element atmatrix[j][i]
.
- Swap rows and columns. The element at position
-
Reverse each row:
- After transposing, reverse the elements in each row to complete the 90-degree rotation.
Input:
- A square matrix (n x n) where
1 <= n <= 20
. - Each matrix element is an integer between
-1000
and1000
.
Output:
- The matrix after rotating it 90 degrees clockwise.
Example 1:
Input:
matrix = [
[1, 2, 3],
[4, 5, 6],
[7, 8, 9]
]
Output:
[
[3, 6, 9],
[2, 5, 8],
[1, 4, 7]
]
Example 2:
Input:
matrix = [
[5, 1, 9, 11],
[2, 4, 8, 10],
[13, 3, 6, 7],
[15, 14, 12, 16]
]
Output:
[
[11, 10, 7, 16],
[9, 8, 6, 12],
[1, 4, 3, 14],
[5, 2, 13, 15]
]
Constraints:
- The matrix is a square matrix, meaning the number of rows and columns are equal.
- Modify the matrix in place (do not use additional matrices).
Code Solution: C Programming Language
#include <stdio.h>
// Function to rotate the matrix 90 degrees clockwise
void rotate(int matrix[][3], int n) {
// Step 1: Transpose the matrix (swap rows with columns)
for (int i = 0; i < n; i++) {
for (int j = i + 1; j < n; j++) { // Start j from i+1 to avoid duplicate swaps
int temp = matrix[i][j];
matrix[i][j] = matrix[j][i];
matrix[j][i] = temp;
}
}
// Step 2: Reverse each row
for (int i = 0; i < n; i++) {
for (int j = 0; j < n / 2; j++) {
int temp = matrix[i][j];
matrix[i][j] = matrix[i][n - 1 - j];
matrix[i][n - 1 - j] = temp;
}
}
}
// Function to print the matrix
void printMatrix(int matrix[][3], int n) {
for (int i = 0; i < n; i++) {
for (int j = 0; j < n; j++) {
printf("%d ", matrix[i][j]);
}
printf("n");
}
}
int main() {
// Input matrix
int matrix[3][3] = {
{1, 2, 3},
{4, 5, 6},
{7, 8, 9}
};
int n = 3;
// Rotate and print the matrix
printf("Original Matrix:n");
printMatrix(matrix, n);
rotate(matrix, n);
printf("nRotated Matrix:n");
printMatrix(matrix, n);
return 0;
}