Given an N * N 2D integer matrix, rotate the matrix by 90 degrees clockwise.
The rotation must be done in place, meaning the input 2D matrix must be modified directly.
Input: matrix = [[1, 2, 3], [4, 5, 6], [7, 8, 9]]
Output: matrix = [[7, 4, 1], [8, 5, 2], [9, 6, 3]]
Input: matrix = [[0, 1, 1, 2], [2, 0, 3, 1], [4, 5, 0, 5], [5, 6, 7, 0]]
Output: matrix = [[5, 4, 2, 0], [6, 5, 0, 1], [7, 0, 3, 1], [0, 5, 1, 2]]
Input: matrix = [[1, 1, 2], [5, 3, 1], [5, 3, 5]]
The naive way is to take another dummy matrix of row and column same as original matrix. Then, take the first row of the original matrix and place it in the last column of the dummy matrix. Next, take the second row of the original matrix and place it in the second last column of the dummy matrix, continuing this process until the last row of the original matrix is placed in the first column of the dummy matrix.
Finally, copy the elements of the dummy matrix back to the original matrix. This procedure ensures that the original matrix is rotated by 90 degrees clockwise.
sizeOfArray
#include<bits/stdc++.h>
using namespace std;
class Solution {
public:
/* Function to rotate the given
matrix by 90 degrees clockwise*/
void rotateMatrix(vector<vector<int>>& matrix) {
/* Get the size of the matrix
(assuming it's a square matrix)*/
int n = matrix.size();
// Initialize new matrix to store rotated values
vector<vector<int>> rotated(n, vector<int>(n, 0));
// Iterate through elements of original matrix
for (int i = 0; i < n; i++) {
for (int j = 0; j < n; j++) {
/* Rotate the element to its new
position in the rotated matrix
New position is (j, n - i - 1)
in the rotated matrix*/
rotated[j][n - i - 1] = matrix[i][j];
}
}
//copy rotated elements to matrix
for(int i = 0; i < rotated.size(); i++){
for(int j = 0; j < rotated[0].size(); j++){
matrix[i][j] = rotated[i][j];
}
}
}
};
int main() {
vector<vector<int>> arr = {{1, 2, 3}, {4, 5, 6}, {7, 8, 9}};
// Create an instance of the Solution class
Solution sol;
sol.rotate(arr);
// Print the rotated matrix
cout << "Rotated Image" << endl;
for (int i = 0; i < arr.size(); i++) {
for (int j = 0; j < arr[0].size(); j++) {
cout << arr[i][j] << " ";
}
cout << endl;
}
return 0;
}
import java.util.*;
class Solution {
//Function to rotate the given matrix by 90 degrees clockwise
public void rotateMatrix(int[][] matrix) {
int n = matrix.length;
// Initialize new matrix to store rotated values
int[][] rotated = new int[n][n];
// Perform rotation logic
for (int i = 0; i < n; i++) {
for (int j = 0; j < n; j++) {
rotated[j][n - i - 1] = matrix[i][j];
}
}
// Copy rotated elements tooriginal matrix
for (int i = 0; i < n; i++) {
System.arraycopy(rotated[i], 0, matrix[i], 0, n);
}
}
public static void main(String[] args) {
int[][] arr = {{1, 2, 3}, {4, 5, 6}, {7, 8, 9}};
// Create an instance of the Solution class
Solution sol = new Solution();
// Rotate the matrix
sol.rotate(arr);
// Print the rotated matrix
System.out.println("Rotated Image");
for (int i = 0; i < arr.length; i++) {
for (int j = 0; j < arr[0].length; j++) {
System.out.print(arr[i][j] + " ");
}
System.out.println();
}
}
}
from typing import List
class Solution:
#Function to rotate the given matrix by 90 degrees clockwise
def rotateMatrix(self, matrix: List[List[int]]) -> None:
n = len(matrix)
# Initialize new matrix to store rotated values
rotated = [[0] * n for _ in range(n)]
# Perform rotation logic
for i in range(n):
for j in range(n):
rotated[j][n - i - 1] = matrix[i][j]
# Copy rotated elements back to original matrix
for i in range(n):
matrix[i] = rotated[i]
if __name__ == "__main__":
arr = [[1, 2, 3], [4, 5, 6], [7, 8, 9]]
# Create an instance of the Solution class
sol = Solution()
# Rotate the matrix
sol.rotate(arr)
# Print the rotated matrix
print("Rotated Image:")
for row in arr:
print(" ".join(map(str, row)))
class Solution {
//Function to rotate the given matrix by 90 degrees clockwise
rotateMatrix(matrix) {
let n = matrix.length;
// Initialize new matrix to store rotated values
let rotated = new Array(n).fill().map(() => new Array(n).fill(0));
// Perform rotation logic
for (let i = 0; i < n; i++) {
for (let j = 0; j < n; j++) {
rotated[j][n - i - 1] = matrix[i][j];
}
}
// Copy rotated elements back to original matrix
for (let i = 0; i < n; i++) {
for (let j = 0; j < n; j++) {
matrix[i][j] = rotated[i][j];
}
}
}
}
let arr = [[1, 2, 3], [4, 5, 6], [7, 8, 9]];
let sol = new Solution();
// Rotate the matrix
sol.rotate(arr);
// Print the rotated matrix
console.log("Rotated Image:");
for (let row of arr) {
console.log(row.join(" "));
}
The optimal way is to find the transpose of the matrix, which ensures that the first row of the matrix becomes the first column, the second row becomes the second column, and so on. Then, reverse each row. This method ensures that the array is rotated 90 degrees without using extra space.
#include <bits/stdc++.h>
using namespace std;
class Solution {
public:
/* Rotate the given matrix
by 90 degrees clockwise.
*/
void rotateMatrix(vector<vector<int>>& matrix) {
int n = matrix.size();
// Transpose the matrix
for (int i = 0; i < n; i++) {
for (int j = 0; j < i; j++) {
swap(matrix[i][j], matrix[j][i]);
}
}
// Reverse each row of the matrix
for (int i = 0; i < n; i++) {
reverse(matrix[i].begin(), matrix[i].end());
}
}
};
int main() {
vector<vector<int>> arr = {{1, 2, 3}, {4, 5, 6}, {7, 8, 9}};
// Create an instance of the Solution class
Solution sol;
// Rotate the matrix
sol.rotate(arr);
// Output the rotated matrix
cout << "Rotated Image" << endl;
for (int i = 0; i < arr.size(); i++) {
for (int j = 0; j < arr[0].size(); j++) {
cout << arr[i][j] << " ";
}
cout << endl;
}
return 0;
}
class Solution {
//Rotate the given matrix by 90 degrees clockwise.
public void rotateMatrix(int[][] matrix) {
int n = matrix.length;
// Transpose the matrix
for (int i = 0; i < n; i++) {
for (int j = 0; j < i; j++) {
// Swap elements across the diagonal
int temp = matrix[i][j];
matrix[i][j] = matrix[j][i];
matrix[j][i] = temp;
}
}
// Reverse each row of the matrix
for (int i = 0; i < n; i++) {
for (int j = 0; j < n / 2; j++) {
// Swap elements symmetrically
int temp = matrix[i][j];
matrix[i][j] = matrix[i][n - 1 - j];
matrix[i][n - 1 - j] = temp;
}
}
}
public static void main(String[] args) {
int[][] arr = {{1, 2, 3}, {4, 5, 6}, {7, 8, 9}};
// Create an instance of the Solution class
Solution sol = new Solution();
// Rotate the matrix
sol.rotate(arr);
// Output the rotated matrix
System.out.println("Rotated Image:");
for (int i = 0; i < arr.length; i++) {
for (int j = 0; j < arr[0].length; j++) {
System.out.print(arr[i][j] + " ");
}
System.out.println();
}
}
}
from typing import List
class Solution:
# Rotate the given matrix by 90 degrees clockwise.
def rotateMatrix(self, matrix: List[List[int]]) -> None:
n = len(matrix)
# Transpose the matrix
for i in range(n):
for j in range(i):
# Swap elements across the diagonal
matrix[i][j], matrix[j][i] = matrix[j][i], matrix[i][j]
# Reverse each row of the matrix
for i in range(n):
for j in range(n // 2):
# Swap elements symmetrically
matrix[i][j], matrix[i][n - 1 - j] = matrix[i][n - 1 - j], matrix[i][j]
if __name__ == "__main__":
arr = [[1, 2, 3], [4, 5, 6], [7, 8, 9]]
# Create an instance of the Solution class
sol = Solution()
# Rotate the matrix
sol.rotate(arr)
# Output the rotated matrix
print("Rotated Image:")
for row in arr:
print(" ".join(map(str, row)))
class Solution {
// Rotate the given matrix by 90 degrees clockwise.
rotateMatrix(matrix) {
let n = matrix.length;
// Transpose the matrix
for (let i = 0; i < n; i++) {
for (let j = 0; j < i; j++) {
// Swap elements across the diagonal
[matrix[i][j], matrix[j][i]] = [matrix[j][i], matrix[i][j]];
}
}
// Reverse each row of the matrix
for (let i = 0; i < n; i++) {
for (let j = 0; j < Math.floor(n / 2); j++) {
// Swap elements symmetrically
[matrix[i][j], matrix[i][n - 1 - j]] = [matrix[i][n - 1 - j], matrix[i][j]];
}
}
}
}
// Example usage:
let arr = [[1, 2, 3], [4, 5, 6], [7, 8, 9]];
// Create an instance of the Solution class
let sol = new Solution();
// Rotate the matrix
sol.rotate(arr);
// Output the rotated matrix
console.log("Rotated Image:");
for (let row of arr) {
console.log(row.join(" "));
}
Q: How does the algorithm handle non-square matrices?
A: The given problem assumes a square N×N matrix. For non-square matrices, a 90-degree rotation would not be in place, as the dimensions change. Handling non-square matrices requires creating a new matrix to store the result.
Q: Why does transposing and reversing achieve a 90-degree rotation?
A: Transposing: Converts rows into columns (flipping the matrix across its diagonal). Reversing Each Row: Aligns the transposed columns to their new positions after rotation.
Q: How would you generalize this for multiple rotations?
A: For k rotations of 90 degrees: Reduce k modulo 4 (k%4) to minimize redundant rotations. Perform the k rotations iteratively using the 90-degree rotation logic.
Q: What if the matrix is sparse?
A: For sparse matrices: Use a coordinate-based representation (e.g., a dictionary of non-zero values). Transform the coordinates for the rotation rather than manipulating the entire matrix. This reduces both time and space complexity for large sparse matrices.