Given an image represented by m x n matrix, rotate the image by 90 degrees in clockwise direction. Please note the dimensions of the result matrix are going to n x m for an m x n input matrix.
Input: 1 2 3 4
5 6 7 8
9 10 11 12
13 14 15 16
Output: 13 9 5 1
14 10 6 2
15 11 7 3
16 12 8 4Another Example:
[Best Approach] – O(m x n) Time
We mainly need to move first row elements to last column, second row elements to second last column.
Let us first try to find out a pattern to solve the problem for a 4 x 4 matrix.
mat[0][0] goes to mat[0][3]
mat[0][1] goes to mat[1][3]
………………………………………
mat[1][0] goes to mat[0][2]
……………………………………..
mat[3][3] goes to mat[3][0]
Do you see a pattern? Mainly we need to move mat[i][j] to mat[j][n-i-1].
#include <bits/stdc++.h>
using namespace std;
vector<vector<int>> rotateMatrix(vector<vector<int>>& mat) {
int m = mat.size();
int n = mat[0].size();
// Create a result matrix of size n x m
vector<vector<int>> res(n, vector<int>(m));
// Move mat[i][j] to res[j][m - i- 1]
for (int i = 0; i < m; i++) {
for (int j = 0; j < n; j++) {
res[j][m - i - 1] = mat[i][j];
}
}
return res;
}
int main() {
vector<vector<int>> mat{
{ 1, 2, 3, 4 },
{ 5, 6, 7, 8 },
{ 9, 10, 11, 12 },
};
vector<vector<int>> res = rotateMatrix(mat);
for (auto& row : res) {
for (auto& x : row)
cout << x << " ";
cout << endl;
}
return 0;
}
public class MatrixRotation {
// Function to rotate a N x M matrix by 90 degrees in clockwise direction
static void rotateMatrix(int[][] mat) {
int n = mat.length;
int m = mat[0].length;
int[][] newMat = new int[m][n];
for (int i = 0; i < n; i++) {
for (int j = 0; j < m; j++) {
newMat[j][n - i - 1] = mat[i][j];
}
}
// Copy the rotated matrix back to the original matrix
mat = newMat;
}
// Function to print the matrix
static void displayMatrix(int[][] mat) {
int n = mat.length;
int m = mat[0].length;
for (int i = 0; i < n; i++) {
for (int j = 0; j < m; j++) {
System.out.print(mat[i][j] + " ");
}
System.out.println();
}
}
public static void main(String[] args) {
// Test Case 1
int[][] mat = {
{1, 2, 3, 4},
{5, 6, 7, 8},
{9, 10, 11, 12}
};
// Function call to rotate the matrix
rotateMatrix(mat);
// Print the rotated matrix
displayMatrix(mat);
}
}
# Function to rotate a N x M matrix by 90 degrees in clockwise direction
def rotateMatrix(mat):
n = len(mat)
m = len(mat[0])
new_mat = [[0] * n for _ in range(m)]
for i in range(n):
for j in range(m):
new_mat[j][n - i - 1] = mat[i][j]
return new_mat
# Function to print the matrix
def displayMatrix(mat):
n = len(mat)
m = len(mat[0])
for i in range(n):
for j in range(m):
print(mat[i][j], end=" ")
print()
print()
# Driver code
if __name__ == "__main__":
# Test Case 1
mat = [
[1, 2, 3, 4],
[5, 6, 7, 8],
[9, 10, 11, 12],
]
# Function call to rotate matrix
mat = rotateMatrix(mat)
# Print rotated matrix
displayMatrix(mat)
using System;
using System.Collections.Generic;
class Program
{
// Function to rotate a matrix by 90 degrees clockwise
static void RotateMatrix(List<List<int>> mat)
{
int n = mat.Count; // Number of rows in the original matrix
int m = mat[0].Count; // Number of columns in the original matrix
// Create a new matrix with dimensions swapped (m x n)
List<List<int>> newMat = new List<List<int>>();
for (int i = 0; i < m; i++)
{
newMat.Add(new List<int>());
for (int j = 0; j < n; j++)
{
newMat[i].Add(0);
}
}
// Fill the new matrix with rotated values
for (int i = 0; i < n; i++)
{
for (int j = 0; j < m; j++)
{
newMat[j][n - i - 1] = mat[i][j];
}
}
// Replace the original matrix with the rotated matrix
mat.Clear();
mat.AddRange(newMat);
}
// Function to display a matrix
static void DisplayMatrix(List<List<int>> mat)
{
int n = mat.Count; // Number of rows in the matrix
int m = mat[0].Count; // Number of columns in the matrix
for (int i = 0; i < n; i++)
{
for (int j = 0; j < m; j++)
{
Console.Write(mat[i][j] + " ");
}
Console.WriteLine();
}
Console.WriteLine();
}
static void Main(string[] args)
{
// Test Case 1: Define a 3x4 matrix
List<List<int>> mat = new List<List<int>>
{
new List<int> { 1, 2, 3, 4 },
new List<int> { 5, 6, 7, 8 },
new List<int> { 9, 10, 11, 12 },
};
// Function call to rotate the matrix
RotateMatrix(mat);
// Display the rotated matrix
DisplayMatrix(mat);
}
}
// Function to rotate a
// 90 x 90 matrix by
// 90 degrees clockwise
function rotateMatrix(mat) {
const n = mat.length;
const m = mat[0].length;
const newMat = new Array(m).fill(0).map(() => new Array(n).fill(0));
for (let i = 0; i < n; i++) {
for (let j = 0; j < m; j++) {
newMat[j][n - i - 1] = mat[i][j];
}
}
return newMat;
}
// Function to print the matrix
function displayMatrix(mat) {
const n = mat.length;
const m = mat[0].length;
for (let i = 0; i < n; i++) {
let row = '';
for (let j = 0; j < m; j++) {
row += mat[i][j] + ' ';
}
console.log(row);
}
console.log('');
}
// Driver code
// Test Case 1
const mat = [
[1, 2, 3, 4],
[5, 6, 7, 8],
[9, 10, 11, 12],
];
// Function call
const rotatedMat = rotateMatrix(mat);
// Print rotated matrix
displayMatrix(rotatedMat);
Output
9 5 1 10 6 2 11 7 3 12 8 4
[Alternate Approach] – O(m x n) Time
When you think about rotating a matrix 90 degrees clockwise, each element moves to a new position. The top row becomes the right column, the second row becomes the second-right column, and so forth. If we first transpose the matrix and then find reverse of every row, we get the desired result.
Follow the given steps to solve the problem:
- Perform Transpose of the matrix
- Reverse every individual row of the matrix
1 2 3 1 4 7 7 4 1
4 5 6 —Transpose-> 2 5 8 —-Reverse rows—-> 8 5 2
7 8 9 3 6 9 9 6 3
#include <algorithm>
#include <iostream>
#include <vector>
using namespace std;
vector<vector<int>> rotateMatrix(vector<vector<int>>& mat) {
// Transpose the matrix
int m = mat.size(), n = mat[0].size();
vector<vector<int>> res(n, vector<int>(m));
for (int i = 0; i < m; i++) {
for (int j = 0; j < n; j++) {
res[j][i] = mat[i][j];
}
}
// Reverse each row to rotate 90 degrees clockwise
for (auto& row : res) {
reverse(row.begin(), row.end());
}
return res;
}
int main() {
vector<vector<int>> mat = {
{ 1, 2, 3, 4 },
{ 5, 6, 7, 8 },
{ 9, 10, 11, 12 }
};
vector<vector<int>> res = rotateMatrix(mat);
for (auto& row : res) {
for (int i = 0; i < row.size(); i++) {
cout << row[i] << " ";
}
cout << endl;
}
return 0;
}
import java.util.ArrayList;
public class ImageRotation {
public static void main(String[] args) {
// Define input image as a 2D ArrayList of pixels
ArrayList<ArrayList<Integer>> image = new ArrayList<>();
image.add(new ArrayList<Integer>() {{
add(1);
add(2);
add(3);
add(4);
}});
image.add(new ArrayList<Integer>() {{
add(5);
add(6);
add(7);
add(8);
}});
image.add(new ArrayList<Integer>() {{
add(9);
add(10);
add(11);
add(12);
}});
// Transpose image matrix
ArrayList<ArrayList<Integer>> transposedImage = new ArrayList<>();
for (int i = 0; i < image.get(0).size(); i++) {
ArrayList<Integer> row = new ArrayList<>();
for (int j = 0; j < image.size(); j++) {
row.add(image.get(j).get(i));
}
transposedImage.add(row);
}
// Reverse the order of rows to rotate the image by 90 degrees counterclockwise
ArrayList<ArrayList<Integer>> rotatedImage = new ArrayList<>();
for (int i = 0; i < transposedImage.size(); i++) {
ArrayList<Integer> row = new ArrayList<>();
for (int j = transposedImage.get(i).size() - 1; j >= 0; j--) {
row.add(transposedImage.get(i).get(j));
}
rotatedImage.add(row);
}
// Print rotated image
for (int i = 0; i < rotatedImage.size(); i++) {
System.out.print("[");
for (int j = 0; j < rotatedImage.get(0).size(); j++) {
System.out.print(rotatedImage.get(i).get(j));
if (j < rotatedImage.get(0).size() - 1) {
System.out.print(", ");
}
}
System.out.println("]");
}
}
}
# define input image as a 2D list of pixels
image = [[1, 2, 3, 4],
[5, 6, 7, 8],
[9, 10, 11, 12]]
# transpose image matrix
transposed_image = [[image[j][i] for j in range(len(image))] for i in range(len(image[0]))]
# reverse the order of rows to rotate the image by 90 degrees counterclockwise
rotated_image = [list(reversed(row)) for row in transposed_image]
# print rotated image
for row in rotated_image:
print(row)
using System;
class Program {
static void Main(string[] args)
{
// Define input image as a 2D array of pixels
int[, ] image = new int[, ] { { 1, 2, 3, 4 },
{ 5, 6, 7, 8 },
{ 9, 10, 11, 12 } };
// Transpose image matrix
int[, ] transposed_image
= new int[image.GetLength(1),
image.GetLength(0)];
for (int i = 0; i < image.GetLength(0); i++) {
for (int j = 0; j < image.GetLength(1); j++) {
transposed_image[j, i] = image[i, j];
}
}
// Reverse the order of columns to rotate the image
// by 90 degrees counterclockwise
int[, ] rotated_image
= new int[transposed_image.GetLength(0),
transposed_image.GetLength(1)];
for (int i = 0; i < transposed_image.GetLength(0);
i++) {
for (int j = 0;
j < transposed_image.GetLength(1); j++) {
rotated_image[i, j] = transposed_image
[i,
transposed_image.GetLength(1) - 1 - j];
}
}
// Print rotated image
for (int i = 0; i < rotated_image.GetLength(0);
i++) {
Console.Write("[");
for (int j = 0; j < rotated_image.GetLength(1);
j++) {
Console.Write(rotated_image[i, j] + ", ");
}
Console.WriteLine("]");
}
}
}
// define input image as a 2D array of pixels
const image = [[1, 2, 3, 4],
[5, 6, 7, 8],
[9, 10, 11, 12]];
// transpose image matrix
const transposedImage = image[0].map((_, i) => image.map(row => row[i]));
// reverse the order of rows to rotate the image by 90 degrees counterclockwise
const rotatedImage = transposedImage.map(row => row.reverse());
// print rotated image
for (let row of rotatedImage) {
console.log(row);
}
Output
9 5 1 10 6 2 11 7 3 12 8 4
Refer to the below article for rotating the square matrix by 90 degrees inplace.
