Given a matrix, clockwise rotate elements in it.
Examples:
Input 1 2 3 4 5 6 7 8 9 Output: 4 1 2 7 5 3 8 9 6 For 4*4 matrix Input: 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 Output: 5 1 2 3 9 10 6 4 13 11 7 8 14 15 16 12
The idea is to use loops similar to the program for printing a matrix in spiral form. One by one rotate all rings of elements, starting from the outermost. To rotate a ring, we need to do following.
- Move elements of top row.Â
- Move elements of last column.Â
- Move elements of bottom row.Â
- Move elements of first column.Â
Repeat above steps for inner ring while there is an inner ring.
Below is the implementation of above idea. Thanks to Gaurav Ahirwar for suggesting below solution.Â
C++
// C++ program to rotate a matrix Â
#include <bits/stdc++.h> #define R 4 #define C 4 using namespace std; Â
// A function to rotate a matrix mat[][] of size R x C. // Initially, m = R and n = C void rotatematrix( int m, int n, int mat[R][C]) { Â Â Â Â int row = 0, col = 0; Â Â Â Â int prev, curr; Â
    /*     row - Starting row index     m - ending row index     col - starting column index     n - ending column index     i - iterator     */     while (row < m && col < n)     { Â
        if (row + 1 == m || col + 1 == n)             break ; Â
        // Store the first element of next row, this         // element will replace first element of current         // row         prev = mat[row + 1][col]; Â
        /* Move elements of first row from the remaining rows */         for ( int i = col; i < n; i++)         {             curr = mat[row][i];             mat[row][i] = prev;             prev = curr;         }         row++; Â
        /* Move elements of last column from the remaining columns */         for ( int i = row; i < m; i++)         {             curr = mat[i][n-1];             mat[i][n-1] = prev;             prev = curr;         }         n--; Â
        /* Move elements of last row from the remaining rows */         if (row < m)         {             for ( int i = n-1; i >= col; i--)             {                 curr = mat[m-1][i];                 mat[m-1][i] = prev;                 prev = curr;             }         }         m--; Â
        /* Move elements of first column from the remaining rows */         if (col < n)         {             for ( int i = m-1; i >= row; i--)             {                 curr = mat[i][col];                 mat[i][col] = prev;                 prev = curr;             }         }         col++;     } Â
    // Print rotated matrix     for ( int i=0; i<R; i++)     {         for ( int j=0; j<C; j++)         cout << mat[i][j] << " " ;         cout << endl;     } } Â
/* Driver program to test above functions */ int main() { Â Â Â Â // Test Case 1 Â Â Â Â int a[R][C] = { {1, 2, 3, 4}, Â Â Â Â Â Â Â Â {5, 6, 7, 8}, Â Â Â Â Â Â Â Â {9, 10, 11, 12}, Â Â Â Â Â Â Â Â {13, 14, 15, 16} }; Â
    // Test Case 2     /* int a[R][C] = {{1, 2, 3},                     {4, 5, 6},                     {7, 8, 9}                     };     */ rotatematrix(R, C, a);     return 0; } |
Java
// Java program to rotate a matrix import java.lang.*; import java.util.*; Â
class GFG { Â Â Â Â static int R = 4 ; Â Â Â Â static int C = 4 ; Â
    // A function to rotate a matrix     // mat[][] of size R x C.     // Initially, m = R and n = C     static void rotatematrix( int m,                     int n, int mat[][])     {         int row = 0 , col = 0 ;         int prev, curr; Â
        /*         row - Starting row index         m - ending row index         col - starting column index         n - ending column index         i - iterator         */         while (row < m && col < n)         {                  if (row + 1 == m || col + 1 == n)                 break ;                  // Store the first element of next             // row, this element will replace             // first element of current row             prev = mat[row + 1 ][col];                  // Move elements of first row             // from the remaining rows             for ( int i = col; i < n; i++)             {                 curr = mat[row][i];                 mat[row][i] = prev;                 prev = curr;             }             row++;                  // Move elements of last column             // from the remaining columns             for ( int i = row; i < m; i++)             {                 curr = mat[i][n- 1 ];                 mat[i][n- 1 ] = prev;                 prev = curr;             }             n--;                  // Move elements of last row             // from the remaining rows             if (row < m)             {                 for ( int i = n- 1 ; i >= col; i--)                 {                     curr = mat[m- 1 ][i];                     mat[m- 1 ][i] = prev;                     prev = curr;                 }             }             m--;                  // Move elements of first column             // from the remaining rows             if (col < n)             {                 for ( int i = m- 1 ; i >= row; i--)                 {                     curr = mat[i][col];                     mat[i][col] = prev;                     prev = curr;                 }             }             col++;         } Â
            // Print rotated matrix             for ( int i = 0 ; i < R; i++)             {                 for ( int j = 0 ; j < C; j++)                 System.out.print( mat[i][j] + " " );                 System.out.print( "\n" );             }     } Â
/* Driver program to test above functions */ Â Â Â Â public static void main(String[] args) Â Â Â Â { Â Â Â Â // Test Case 1 Â Â Â Â int a[][] = { { 1 , 2 , 3 , 4 }, Â Â Â Â Â Â Â Â Â Â Â Â Â Â Â Â Â Â { 5 , 6 , 7 , 8 }, Â Â Â Â Â Â Â Â Â Â Â Â Â Â Â Â { 9 , 10 , 11 , 12 }, Â Â Â Â Â Â Â Â Â Â Â Â Â Â Â Â { 13 , 14 , 15 , 16 } }; Â
    // Test Case 2     /* int a[][] = new int {{1, 2, 3},                             {4, 5, 6},                             {7, 8, 9}                         };*/     rotatematrix(R, C, a);          } } Â
// This code is contributed by Sahil_Bansall |
Python
# Python program to rotate a matrix Â
# Function to rotate a matrix def rotateMatrix(mat): Â
    if not len (mat):         return          """         top : starting row index         bottom : ending row index         left : starting column index         right : ending column index     """ Â
    top = 0     bottom = len (mat) - 1 Â
    left = 0     right = len (mat[ 0 ]) - 1 Â
    while left < right and top < bottom: Â
        # Store the first element of next row,         # this element will replace first element of         # current row         prev = mat[top + 1 ][left] Â
        # Move elements of top row one step right         for i in range (left, right + 1 ):             curr = mat[top][i]             mat[top][i] = prev             prev = curr Â
        top + = 1 Â
        # Move elements of rightmost column one step downwards         for i in range (top, bottom + 1 ):             curr = mat[i][right]             mat[i][right] = prev             prev = curr Â
        right - = 1 Â
        # Move elements of bottom row one step left         for i in range (right, left - 1 , - 1 ):             curr = mat[bottom][i]             mat[bottom][i] = prev             prev = curr Â
        bottom - = 1 Â
        # Move elements of leftmost column one step upwards         for i in range (bottom, top - 1 , - 1 ):             curr = mat[i][left]             mat[i][left] = prev             prev = curr Â
        left + = 1 Â
    return mat Â
# Utility Function def printMatrix(mat): Â Â Â Â for row in mat: Â Â Â Â Â Â Â Â print row Â
Â
# Test case 1 matrix = [             [ 1 , 2 , 3 , 4 ],             [ 5 , 6 , 7 , 8 ],             [ 9 , 10 , 11 , 12 ],             [ 13 , 14 , 15 , 16 ]         ] # Test case 2 """ matrix =[             [1, 2, 3],             [4, 5, 6],             [7, 8, 9]         ] """ Â
matrix = rotateMatrix(matrix) # Print modified matrix printMatrix(matrix) |
C#
// C# program to rotate a matrix using System; Â
class GFG { Â Â Â Â Â Â Â Â Â static int R = 4; Â Â Â Â static int C = 4; Â
    // A function to rotate a matrix     // mat[][] of size R x C.     // Initially, m = R and n = C     static void rotatematrix( int m,                         int n, int [,]mat)     {         int row = 0, col = 0;         int prev, curr; Â
        /*         row - Starting row index         m - ending row index         col - starting column index         n - ending column index         i - iterator         */         while (row < m && col < n)         {                  if (row + 1 == m || col + 1 == n)                 break ;                  // Store the first element of next             // row, this element will replace             // first element of current row             prev = mat[row + 1, col];                  // Move elements of first row             // from the remaining rows             for ( int i = col; i < n; i++)             {                 curr = mat[row,i];                 mat[row, i] = prev;                 prev = curr;             }             row++;                  // Move elements of last column             // from the remaining columns             for ( int i = row; i < m; i++)             {                 curr = mat[i,n-1];                 mat[i, n-1] = prev;                 prev = curr;             }             n--;                  // Move elements of last row             // from the remaining rows             if (row < m)             {                 for ( int i = n-1; i >= col; i--)                 {                     curr = mat[m-1,i];                     mat[m-1,i] = prev;                     prev = curr;                 }             }             m--;                  // Move elements of first column             // from the remaining rows             if (col < n)             {                 for ( int i = m-1; i >= row; i--)                 {                     curr = mat[i,col];                     mat[i,col] = prev;                     prev = curr;                 }             }             col++;         } Â
            // Print rotated matrix             for ( int i = 0; i < R; i++)             {                 for ( int j = 0; j < C; j++)                 Console.Write( mat[i,j] + " " );                 Console.Write( "\n" );             }     } Â
    /* Driver program to test above functions */     public static void Main()     {         // Test Case 1         int [,]a = { {1, 2, 3, 4},                     {5, 6, 7, 8},                     {9, 10, 11, 12},                     {13, 14, 15, 16} };              // Test Case 2         /* int a[][] = new int {{1, 2, 3},                                 {4, 5, 6},                                 {7, 8, 9}                             };*/         rotatematrix(R, C, a);              } } Â
// This code is contributed by nitin mittal. |
PHP
<?php // PHP program to rotate a matrix $R = 4; $C = 4; Â
// A function to rotate a matrix // mat[][] of size R x C. Initially, // m = R and n = C function rotatematrix( $m , $n , $mat ) { Â Â Â Â global $R , $C ; Â Â Â Â $row = 0; Â Â Â Â $col = 0; Â Â Â Â $prev = 0; Â Â Â Â $curr = 0; Â
    /*     row - Starting row index     m - ending row index     col - starting column index     n - ending column index     i - iterator     */     while ( $row < $m && $col < $n )     { Â
        if ( $row + 1 == $m ||             $col + 1 == $n )             break ; Â
        // Store the first element         // of next row, this element         // will replace first element         // of current row         $prev = $mat [ $row + 1][ $col ]; Â
        /* Move elements of first row            from the remaining rows */         for ( $i = $col ; $i < $n ; $i ++)         {             $curr = $mat [ $row ][ $i ];             $mat [ $row ][ $i ] = $prev ;             $prev = $curr ;         }         $row ++; Â
        /* Move elements of last column            from the remaining columns */         for ( $i = $row ; $i < $m ; $i ++)         {             $curr = $mat [ $i ][ $n - 1];             $mat [ $i ][ $n - 1] = $prev ;             $prev = $curr ;         }         $n --; Â
        /* Move elements of last row            from the remaining rows */         if ( $row < $m )         {             for ( $i = $n - 1;                  $i >= $col ; $i --)             {                 $curr = $mat [ $m - 1][ $i ];                 $mat [ $m - 1][ $i ] = $prev ;                 $prev = $curr ;             }         }         $m --; Â
        /* Move elements of first column            from the remaining rows */         if ( $col < $n )         {             for ( $i = $m - 1;                  $i >= $row ; $i --)             {                 $curr = $mat [ $i ][ $col ];                 $mat [ $i ][ $col ] = $prev ;                 $prev = $curr ;             }         }         $col ++;     } Â
    // Print rotated matrix     for ( $i = 0; $i < $R ; $i ++)     {         for ( $j = 0; $j < $C ; $j ++)         echo $mat [ $i ][ $j ] . " " ;         echo "\n" ;     } } Â
// Driver code Â
// Test Case 1 $a = array ( array (1, 2, 3, 4), Â Â Â Â Â Â Â Â Â Â Â array (5, 6, 7, 8), Â Â Â Â Â Â Â Â Â Â Â array (9, 10, 11, 12), Â Â Â Â Â Â Â Â Â Â Â array (13, 14, 15, 16)); Â
// Test Case 2 /* int $a = array(array(1, 2, 3), Â Â Â Â Â Â Â Â Â Â Â Â Â Â Â Â Â Â array(4, 5, 6), Â Â Â Â Â Â Â Â Â Â Â Â Â Â Â Â Â Â array(7, 8, 9)); */ rotatematrix( $R , $C , $a ); Â Â Â Â return 0; Â Â Â Â Â // This code is contributed // by ChitraNayal ?> |
Javascript
<script> Â
// Javascript program to rotate a matrix   Â
let R = 4; let C = 4; Â
// A function to rotate a matrix // mat[][] of size R x C. // Initially, m = R and n = C function rotatematrix(m, n, mat) {     let row = 0, col = 0;     let prev, curr;          /*     row - Starting row index     m - ending row index     col - starting column index     n - ending column index     i - iterator     */     while (row < m && col < n)     {         if (row + 1 == m || col + 1 == n)             break ;            // Store the first element of next         // row, this element will replace         // first element of current row         prev = mat[row + 1][col];            // Move elements of first row         // from the remaining rows         for (let i = col; i < n; i++)         {             curr = mat[row][i];             mat[row][i] = prev;             prev = curr;         }         row++;            // Move elements of last column         // from the remaining columns         for (let i = row; i < m; i++)         {             curr = mat[i][n - 1];             mat[i][n - 1] = prev;             prev = curr;         }         n--;            // Move elements of last row         // from the remaining rows         if (row < m)         {             for (let i = n - 1; i >= col; i--)             {                 curr = mat[m - 1][i];                 mat[m - 1][i] = prev;                 prev = curr;             }         }         m--;            // Move elements of first column         // from the remaining rows         if (col < n)         {             for (let i = m - 1; i >= row; i--)             {                 curr = mat[i][col];                 mat[i][col] = prev;                 prev = curr;             }         }         col++;     } Â
    // Print rotated matrix     for (let i = 0; i < R; i++)     {         for (let j = 0; j < C; j++)             document.write( mat[i][j] + " " );                      document.write( "<br>" );     } } Â
// Driver code Â
// Test Case 1 let a = [ [ 1, 2, 3, 4 ], Â Â Â Â Â Â Â Â Â Â [ 5, 6, 7, 8 ], Â Â Â Â Â Â Â Â Â Â [ 9, 10, 11, 12 ], Â Â Â Â Â Â Â Â Â Â [ 13, 14, 15, 16 ] ]; Â Â Â Â Â Â Â Â Â Â Â rotatematrix(R, C, a); Â
// This code is contributed by avanitrachhadiya2155 Â
</script> |
5 1 2 3 9 10 6 4 13 11 7 8 14 15 16 12
Complexity Analysis:
- Time Complexity: O(m*n) where m is the number of rows & n is the number of columns.
- Auxiliary Space: O(1).Â
Example: (Rotate anticlockwise – By using vectors in c++)
C++
#include <iostream> #include <vector> Â
using namespace std; Â
// Function to rotate the matrix in a clockwise direction void rotateMatrix(vector<vector< int >> &matrix) { Â Â Â Â int n = matrix.size(); Â
    // Transpose the matrix     for ( int i = 0; i < n; i++) {         for ( int j = i; j < n; j++) {             swap(matrix[i][j], matrix[j][i]);         }     } Â
    // Reverse the columns     for ( int i = 0; i < n; i++) {         for ( int j = 0, k = n - 1; j < k; j++, k--) {             swap(matrix[j][i], matrix[k][i]);         }     } } Â
// Function to print the matrix void printMatrix(vector<vector< int >> &matrix) { Â Â Â Â for ( int i = 0; i < matrix.size(); i++) { Â Â Â Â Â Â Â Â for ( int j = 0; j < matrix[i].size(); j++) { Â Â Â Â Â Â Â Â Â Â Â Â cout << matrix[i][j] << " " ; Â Â Â Â Â Â Â Â } Â Â Â Â Â Â Â Â cout << endl; Â Â Â Â } } Â
int main() { Â Â Â Â vector<vector< int >> matrix = {{1, 2, 3}, {4, 5, 6}, {7, 8, 9}}; Â Â Â Â cout << "Original matrix:" << endl; Â Â Â Â printMatrix(matrix); Â Â Â Â rotateMatrix(matrix); Â Â Â Â cout << "Rotated matrix:" << endl; Â Â Â Â printMatrix(matrix); Â Â Â Â return 0; } |
Java
import java.util.ArrayList; import java.util.List; Â
public class Main { Â
    // Function to rotate the matrix in a clockwise     // direction     public static void     rotateMatrix(List<List<Integer> > matrix)     {         int n = matrix.size(); Â
        // Transpose the matrix         for ( int i = 0 ; i < n; i++) {             for ( int j = i; j < n; j++) {                 int temp = matrix.get(i).get(j);                 matrix.get(i).set(j, matrix.get(j).get(i));                 matrix.get(j).set(i, temp);             }         } Â
        // Reverse the columns         for ( int i = 0 ; i < n; i++) {             for ( int j = 0 , k = n - 1 ; j < k; j++, k--) {                 int temp = matrix.get(j).get(i);                 matrix.get(j).set(i, matrix.get(k).get(i));                 matrix.get(k).set(i, temp);             }         }     } Â
    // Function to print the matrix     public static void     printMatrix(List<List<Integer> > matrix)     {         for ( int i = 0 ; i < matrix.size(); i++) {             for ( int j = 0 ; j < matrix.get(i).size(); j++) {                 System.out.print(matrix.get(i).get(j)                                  + " " );             }             System.out.println();         }     } Â
    public static void main(String[] args)     {         List<List<Integer> > matrix = new ArrayList<>();         matrix.add( new ArrayList<Integer>() {             {                 add( 1 );                 add( 2 );                 add( 3 );             }         });         matrix.add( new ArrayList<Integer>() {             {                 add( 4 );                 add( 5 );                 add( 6 );             }         });         matrix.add( new ArrayList<Integer>() {             {                 add( 7 );                 add( 8 );                 add( 9 );             }         });         System.out.println( "Original matrix:" );         printMatrix(matrix);         rotateMatrix(matrix);         System.out.println( "Rotated matrix:" );         printMatrix(matrix);     } } |
Python3
def rotate_matrix(matrix):     n = len (matrix)          # Transpose the matrix     for i in range (n):         for j in range (i, n):             matrix[i][j], matrix[j][i] = matrix[j][i], matrix[i][j]          # Reverse the columns     for i in range (n):         for j, k in zip ( range (n / / 2 ), range (n - 1 , n / / 2 - 1 , - 1 )):             matrix[j][i], matrix[k][i] = matrix[k][i], matrix[j][i] Â
def print_matrix(matrix): Â Â Â Â for row in matrix: Â Â Â Â Â Â Â Â print ( ' ' .join( str (elem) for elem in row)) Â
matrix = [[ 1 , 2 , 3 ], [ 4 , 5 , 6 ], [ 7 , 8 , 9 ]] print ( "Original matrix:" ) print_matrix(matrix) rotate_matrix(matrix) print ( "Rotated matrix:" ) print_matrix(matrix) |
C#
using System; using System.Collections.Generic; Â
class Program { // Function to rotate the matrix in a clockwise // direction public static void RotateMatrix(List<List< int >> matrix) { int n = matrix.Count;      // Transpose the matrix     for ( int i = 0; i < n; i++) {         for ( int j = i; j < n; j++) {             int temp = matrix[i][j];             matrix[i][j] = matrix[j][i];             matrix[j][i] = temp;         }     } Â
    // Reverse the columns     for ( int i = 0; i < n; i++) {         for ( int j = 0, k = n - 1; j < k; j++, k--) {             int temp = matrix[j][i];             matrix[j][i] = matrix[k][i];             matrix[k][i] = temp;         }     } } Â
// Function to print the matrix public static void PrintMatrix(List<List< int >> matrix) { Â Â Â Â for ( int i = 0; i < matrix.Count; i++) { Â Â Â Â Â Â Â Â for ( int j = 0; j < matrix[i].Count; j++) { Â Â Â Â Â Â Â Â Â Â Â Â Console.Write(matrix[i][j] + " " ); Â Â Â Â Â Â Â Â } Â Â Â Â Â Â Â Â Console.WriteLine(); Â Â Â Â } } Â
static void Main( string [] args) { Â Â Â Â List<List< int >> matrix = new List<List< int >>(); Â Â Â Â matrix.Add( new List< int >() { 1, 2, 3 }); Â Â Â Â matrix.Add( new List< int >() { 4, 5, 6 }); Â Â Â Â matrix.Add( new List< int >() { 7, 8, 9 }); Â
    Console.WriteLine( "Original matrix:" );     PrintMatrix(matrix);     RotateMatrix(matrix);     Console.WriteLine( "Rotated matrix:" );     PrintMatrix(matrix); } } |
Javascript
function rotateMatrix(grid) { Â Â const n = grid.length; Â
  // Transpose the matrix   for (let i = 0; i < n; i++) {     for (let j = i; j < n; j++) {       [grid[i][j], matrix[j][i]] = [grid[j][i], grid[i][j]];     }   } Â
  // Reverse the columns   for (let i = 0; i < n; i++) {     for (let j = 0, k = n - 1; j < k; j++, k--) {       [grid[j][i], matrix[k][i]] = [grid[k][i], matrix[j][i]];     }   } } Â
function printMatrix(matrix) { Â Â for (let i = 0; i < grid.length; i++) { Â Â Â Â let row = "" ; Â Â Â Â for (let j = 0; j < grid[i].length; j++) { Â Â Â Â Â Â row += grid[i][j] + " " ; Â Â Â Â } Â Â Â Â console.log(row); Â Â } } Â
let matrix = [[1, 2, 3], [4, 5, 6], [7, 8, 9]]; console.log( "Original matrix:" ); printMatrix(matrix); rotateMatrix(matrix); console.log( "Rotated matrix:" ); printMatrix(matrix); |
Original matrix: 1 2 3 4 5 6 7 8 9 Rotated matrix: 3 6 9 2 5 8 1 4 7
Complexity Analysis:
Time Complexity:
The time complexity of the given implementation is O(n^2), where n is the size of the matrix. This is because we need to traverse through all the elements of the matrix twice (once for transposing and once for reversing the columns). Therefore, the time complexity of this algorithm is quadratic.
Auxiliary Space:
The auxiliary space complexity of this implementation is O(1), which means that the amount of extra memory required for the algorithm is constant and does not depend on the input size. In this implementation, we are modifying the matrix in-place without using any additional data structure. Therefore, the space required for this algorithm is constant.
Ready to dive in? Explore our Free Demo Content and join our DSA course, trusted by over 100,000 neveropen!
[…] refer complete article on Rotate Matrix Elements for more […]