Open In App

Rotate an Image 90 Degree Counterclockwise

Last Updated : 05 Oct, 2024
Comments
Improve
Suggest changes
Like Article
Like
Report

Given an image represented by m x n matrix, rotate the image by 90 degrees in counterclockwise 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:
4 8 12 16
3 7 11 15
2 6 10 14
1 5 9 13

Input:
1 2 3 4
5 6 7 8
9 10 11 12
Output:
4 8 12
3 7 11
2 6 10
1 5 9

[Best Approach] – O(m x n) Time

We mainly need to move first row elements to first column in revers order, second row elements to second column in reverse order.

Let us first try to find out a pattern to solve the problem for n = 4 (second example matrix above)

mat[0][0] goes to mat[3][0]
mat[0][1] goes to mat[2][0]
………………………………………
mat[1][0] goes to mat[3][1]
……………………………………..
mat[3][3] goes to mat[0][3]

Do you see a pattern? Mainly we need to move mat[i][j] to mat[n-j-1][i].

C++
#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;
}
Java
import java.util.*;

class RotateMatrix {
    static int[][] rotateMatrix(int[][] mat) {
        int m = mat.length;
        int n = mat[0].length;
        
        // Create a result matrix of size n x m
        int[][] res = new int[n][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;
    }

    public static void main(String[] args) {
        int[][] mat = {
            {1, 2, 3, 4},
            {5, 6, 7, 8},
            {9, 10, 11, 12}
        };

        int[][] res = rotateMatrix(mat);

        for (int[] row : res) {
            for (int x : row) {
                System.out.print(x + " ");
            }
            System.out.println();
        }
    }
}
Python
from collections import deque

def rotate_matrix(mat):
    m = len(mat)
    
    # Create a result matrix of size n x m
    res = [[0] * m for _ in range(len(mat[0]))]
    
    # Move mat[i][j] to res[j][m - i - 1]
    for i in range(m):
        for j in range(len(mat[0])):
            res[j][m - i - 1] = mat[i][j]
    
    return res

if __name__ == "__main__":
    mat = [
        [1, 2, 3, 4],
        [5, 6, 7, 8],
        [9, 10, 11, 12]
    ]
    
    res = rotate_matrix(mat)
    
    for row in res:
        print(" ".join(map(str, row)))

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 counterclockwise, each element moves to a new position. The top row becomes the leftmost column, the second row becomes the second-left column, and so forth. If we first transpose the matrix, and then reverse individual columns, we get the desired result.

Follow the given steps to solve the problem:

untitled215
Rotate 90 Degree Anticlockwise
C++
#include <iostream>
#include <vector>
using namespace std;

vector<vector<int>> rotateMatrix(vector<vector<int>> &mat)
{
    int m = mat.size(), n = mat[0].size();
    vector<vector<int>> res(n, vector<int>(m));

    // Transpose the matrix
    for (int i = 0; i < m; i++)
    {
        for (int j = 0; j < n; j++)
        {
            res[j][i] = mat[i][j];
        }
    }

    // Reverse each column of result which is
    // a n x m matrix
    for (int i = 0; i < m; i++)
    {
        for (int j = 0; j < n; j++)
        {
            swap(res[i][j], res[n - i - 1][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 (int i = 0; i < row.size(); i++)
        {
            cout << row[i] << " ";
        }
        cout << endl;
    }

    return 0;
}
Java
import java.util.*;

class RotateMatrix {
    static int[][] rotateMatrix(int[][] mat) {
        int m = mat.length, n = mat[0].length;
        int[][] res = new int[n][m];

        // Transpose the matrix
        for (int i = 0; i < m; i++) {
            for (int j = 0; j < n; j++) {
                res[j][i] = mat[i][j];
            }
        }

        // Reverse each column (not row) of the result which is a n x m matrix
        for (int j = 0; j < m; j++) {
            for (int i = 0; i < n / 2; i++) {
                int temp = res[i][j];
                res[i][j] = res[n - i - 1][j];
                res[n - i - 1][j] = temp;
            }
        }

        return res;
    }

    public static void main(String[] args) {
        int[][] mat = {
            {1, 2, 3, 4},
            {5, 6, 7, 8},
            {9, 10, 11, 12}
        };

        int[][] res = rotateMatrix(mat);

        for (int[] row : res) {
            for (int val : row) {
                System.out.print(val + " ");
            }
            System.out.println();
        }
    }
}
Python
def rotate_matrix(mat):
    m, n = len(mat), len(mat[0])
    res = [[0] * m for _ in range(n)]

    # Transpose the matrix
    for i in range(m):
        for j in range(n):
            res[j][i] = mat[i][j]

    # Reverse each column (not row) of the result which is a n x m matrix
    for j in range(m):
        for i in range(n // 2):
            res[i][j], res[n - i - 1][j] = res[n - i - 1][j], res[i][j]

    return res

if __name__ == "__main__":
    mat = [
        [1, 2, 3, 4],
        [5, 6, 7, 8],
        [9, 10, 11, 12]
    ]

    res = rotate_matrix(mat)

    for row in res:
        print(" ".join(map(str, row)))

Output
4 8 12 
2 6 10 
3 7 11 
1 5 9 


Note : We can alternatively do

  1. Reverse individual rows
  2. Transpose Matrix

Next Article
Article Tags :
Practice Tags :

Similar Reads