The Wayback Machine - https://web.archive.org/web/20240903161259/https://www.geeksforgeeks.org/inplace-rotate-square-matrix-by-90-degrees/
Open In App

Inplace rotate square matrix by 90 degrees | Set 1

Last Updated : 21 Nov, 2023
Comments
Improve
Suggest changes
Like Article
Like
Save
Share
Report
News Follow
Companies:
Show Topics
Solve Problem
Medium
63.1%
32.6K

Given a square matrix, turn it by 90 degrees in an anti-clockwise direction without using any extra space

Examples: 

Input:
Matrix:    1  2  3
               4  5  6
               7  8  9

Output:  3  6  9 
               2  5  8 
               1  4  7 

Input:
Matrix:    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

Note: An approach that requires extra space is already discussed here.

Example no1 – Inplace rotate square matrix by 90 degrees by forming cycles:

To solve the problem follow the below idea:

To solve the question without any extra space, rotate the array in form of squares, dividing the matrix into squares or cycles. For example, 
A 4 X 4 matrix will have 2 cycles. The first cycle is formed by its 1st row, last column, last row, and 1st column. The second cycle is formed by the 2nd row, second-last column, second-last row, and 2nd column. The idea is for each square cycle, to swap the elements involved with the corresponding cell in the matrix in an anti-clockwise direction i.e. from top to left, left to bottom, bottom to right, and from right to top one at a time using nothing but a temporary variable to achieve this

Dry run of the above approach:

First Cycle:

 1  2  3 4 
 5  6  7 8 
 9 10 11 12 
13 14 15 16 

Moving first group of four elements (elements 
of 1st row, last row, 1st column and last column) of first cycle 
in counter clockwise. 

 4  2  3 16
 5  6  7 8 
 9 10 11 12 
 1 14  15 13 

 Moving next group of four elements of 
first cycle in counter clockwise 

 4  8  3 16 
 5  6  7  15  
 2  10 11 12 
 1  14  9 13 

Moving final group of four elements of 
first cycle in counter clockwise 

 4  8 12 16 
 3  6  7 15 
 2 10 11 14 
 1  5  9 13 

Second Cycle:

 4  8 12 16 
 3  6 7  15 
 2  10 11 14 
 1  5  9 13 

Fixing second cycle

 4  8 12 16 
 3  7 11 15 
 2  6 10 14 
 1  5  9 13

Follow the given steps to solve the problem:

  • There are N/2 squares or cycles in a matrix of side N. Process a square one at a time. Run a loop to traverse the matrix a cycle at a time, i.e loop from 0 to N/2 – 1, loop counter is i
  • Consider elements in group of 4 in current square, rotate the 4 elements at a time. So the number of such groups in a cycle is N – 2*i.
  • So run a loop in each cycle from x to N – x – 1, loop counter is y
  • The elements in the current group is (x, y), (y, N-1-x), (N-1-x, N-1-y), (N-1-y, x), now rotate the these 4 elements, i.e (x, y) <- (y, N-1-x), (y, N-1-x)<- (N-1-x, N-1-y), (N-1-x, N-1-y)<- (N-1-y, x), (N-1-y, x)<- (x, y)
  • Print the matrix.

Below is the implementation of the above approach:

C++




// C++ program to rotate a matrix
// by 90 degrees
#include <bits/stdc++.h>
#define N 4
using namespace std;
 
// An Inplace function to
// rotate a N x N matrix
// by 90 degrees in
// anti-clockwise direction
void rotateMatrix(int mat[][N])
{
    // Consider all squares one by one
    for (int x = 0; x < N / 2; x++) {
        // Consider elements in group
        // of 4 in current square
        for (int y = x; y < N - x - 1; y++) {
            // Store current cell in
            // temp variable
            int temp = mat[x][y];
 
            // Move values from right to top
            mat[x][y] = mat[y][N - 1 - x];
 
            // Move values from bottom to right
            mat[y][N - 1 - x] = mat[N - 1 - x][N - 1 - y];
 
            // Move values from left to bottom
            mat[N - 1 - x][N - 1 - y] = mat[N - 1 - y][x];
 
            // Assign temp to left
            mat[N - 1 - y][x] = temp;
        }
    }
}
 
// Function to print the matrix
void displayMatrix(int mat[N][N])
{
    for (int i = 0; i < N; i++) {
        for (int j = 0; j < N; j++) {
            cout << mat[i][j] << " ";
        }
        cout << endl;
    }
    cout << endl;
}
 
/* Driver code */
int main()
{
    // Test Case 1
    int mat[N][N] = { { 1, 2, 3, 4 },
                      { 5, 6, 7, 8 },
                      { 9, 10, 11, 12 },
                      { 13, 14, 15, 16 } };
 
    // Function call
    rotateMatrix(mat);
 
    // Print rotated matrix
    displayMatrix(mat);
 
    return 0;
}


Java




// Java program to rotate a
// matrix by 90 degrees
import java.io.*;
 
class GFG {
    // An Inplace function to
    // rotate a N x N matrix
    // by 90 degrees in
    // anti-clockwise direction
    static void rotateMatrix(int N, int mat[][])
    {
        // Consider all squares one by one
        for (int x = 0; x < N / 2; x++) {
            // Consider elements in group
            // of 4 in current square
            for (int y = x; y < N - x - 1; y++) {
                // Store current cell in
                // temp variable
                int temp = mat[x][y];
 
                // Move values from right to top
                mat[x][y] = mat[y][N - 1 - x];
 
                // Move values from bottom to right
                mat[y][N - 1 - x]
                    = mat[N - 1 - x][N - 1 - y];
 
                // Move values from left to bottom
                mat[N - 1 - x][N - 1 - y]
                    = mat[N - 1 - y][x];
 
                // Assign temp to left
                mat[N - 1 - y][x] = temp;
            }
        }
    }
 
    // Function to print the matrix
    static void displayMatrix(int N, int mat[][])
    {
        for (int i = 0; i < N; i++) {
            for (int j = 0; j < N; j++)
                System.out.print(" " + mat[i][j]);
 
            System.out.print("\n");
        }
        System.out.print("\n");
    }
 
    /* Driver code*/
    public static void main(String[] args)
    {
        int N = 4;
 
        int mat[][] = { { 1, 2, 3, 4 },
                        { 5, 6, 7, 8 },
                        { 9, 10, 11, 12 },
                        { 13, 14, 15, 16 } };
 
        // Function call
        rotateMatrix(N, mat);
 
        // Print rotated matrix
        displayMatrix(N, mat);
    }
}
 
// This code is contributed by Prakriti Gupta


Python3




# Python3 program to rotate a matrix by 90 degrees
N = 4
 
# An Inplace function to rotate
# N x N matrix by 90 degrees in
# anti-clockwise direction
 
 
def rotateMatrix(mat):
 
    # Consider all squares one by one
    for x in range(0, int(N / 2)):
 
        # Consider elements in group
        # of 4 in current square
        for y in range(x, N-x-1):
 
            # store current cell in temp variable
            temp = mat[x][y]
 
            # move values from right to top
            mat[x][y] = mat[y][N-1-x]
 
            # move values from bottom to right
            mat[y][N-1-x] = mat[N-1-x][N-1-y]
 
            # move values from left to bottom
            mat[N-1-x][N-1-y] = mat[N-1-y][x]
 
            # assign temp to left
            mat[N-1-y][x] = temp
 
 
# Function to print the matrix
def displayMatrix(mat):
 
    for i in range(0, N):
 
        for j in range(0, N):
 
            print(mat[i][j], end=' ')
        print("")
 
 
# Driver Code
if __name__ == "__main__":
    mat = [[0 for x in range(N)] for y in range(N)]
 
    mat = [[1, 2, 3, 4],
           [5, 6, 7, 8],
           [9, 10, 11, 12],
           [13, 14, 15, 16]]
 
    # Function call
    rotateMatrix(mat)
 
    # Print rotated matrix
    displayMatrix(mat)
 
 
# This code is contributed by saloni1297


C#




// C# program to rotate a
// matrix by 90 degrees
using System;
 
class GFG {
    // An Inplace function to
    // rotate a N x N matrix
    // by 90 degrees in anti-
    // clockwise direction
    static void rotateMatrix(int N, int[, ] mat)
    {
        // Consider all
        // squares one by one
        for (int x = 0; x < N / 2; x++) {
            // Consider elements
            // in group of 4 in
            // current square
            for (int y = x; y < N - x - 1; y++) {
                // store current cell
                // in temp variable
                int temp = mat[x, y];
 
                // move values from
                // right to top
                mat[x, y] = mat[y, N - 1 - x];
 
                // move values from
                // bottom to right
                mat[y, N - 1 - x]
                    = mat[N - 1 - x, N - 1 - y];
 
                // move values from
                // left to bottom
                mat[N - 1 - x, N - 1 - y]
                    = mat[N - 1 - y, x];
 
                // assign temp to left
                mat[N - 1 - y, x] = temp;
            }
        }
    }
 
    // Function to print the matrix
    static void displayMatrix(int N, int[, ] mat)
    {
        for (int i = 0; i < N; i++) {
            for (int j = 0; j < N; j++)
                Console.Write(" " + mat[i, j]);
            Console.WriteLine();
        }
        Console.WriteLine();
    }
 
    // Driver Code
    static public void Main()
    {
        int N = 4;
 
        int[, ] mat = { { 1, 2, 3, 4 },
                        { 5, 6, 7, 8 },
                        { 9, 10, 11, 12 },
                        { 13, 14, 15, 16 } };
 
        // Function call
        rotateMatrix(N, mat);
 
        // Print rotated matrix
        displayMatrix(N, mat);
    }
}
 
// This code is contributed by ajit


Javascript




<script>
// Javascript program to rotate a
// matrix by 90 degrees
 
    // An Inplace function to
    // rotate a N x N matrix
    // by 90 degrees in
    // anti-clockwise direction
    function rotateMatrix(N,mat)
    {
     
        // Consider all squares one by one
        for (let x = 0; x < N / 2; x++)
        {
         
            // Consider elements in group
            // of 4 in current square
            for (let y = x; y < N - x - 1; y++)
            {
             
                // Store current cell in
                // temp variable
                let temp = mat[x][y];
   
                // Move values from right to top
                mat[x][y] = mat[y][N - 1 - x];
   
                // Move values from bottom to right
                mat[y][N - 1 - x]
                    = mat[N - 1 - x][N - 1 - y];
   
                // Move values from left to bottom
                mat[N - 1 - x][N - 1 - y] = mat[N - 1 - y][x];
   
                // Assign temp to left
                mat[N - 1 - y][x] = temp;
            }
        }
    }
     
    // Function to print the matrix
    function displayMatrix(N,mat)
    {
        for (let i = 0; i < N; i++)
        {
            for (let j = 0; j < N; j++)
                document.write(
                    " " + mat[i][j]);
   
            document.write("<br>");
        }
        document.write("<br>");
    }
     
    /* Driver program to test above functions */
    let N = 4;
    let mat=[[1, 2, 3, 4],[ 5, 6, 7, 8 ],[9, 10, 11, 12 ],[13, 14, 15, 16]];
     
    // displayMatrix(mat);
    rotateMatrix(N, mat);
 
    // Print rotated matrix
    displayMatrix(N, mat);
     
    // This code is contributed by rag2127. 
</script>


PHP




<?php
// PHP program to rotate a
// matrix by 90 degrees
$N = 4;
 
// An Inplace function to
// rotate a N x N matrix
// by 90 degrees in
// anti-clockwise direction
function rotateMatrix(&$mat)
{
    global $N;
     
    // Consider all
    // squares one by one
    for ($x = 0; $x < $N / 2; $x++)
    {
        // Consider elements
        // in group of 4 in
        // current square
        for ($y = $x;
             $y < $N - $x - 1; $y++)
        {
            // store current cell
            // in temp variable
            $temp = $mat[$x][$y];
 
            // move values from
            // right to top
            $mat[$x][$y] = $mat[$y][$N - 1 - $x];
 
            // move values from
            // bottom to right
            $mat[$y][$N - 1 - $x] =
                $mat[$N - 1 - $x][$N - 1 - $y];
 
            // move values from
            // left to bottom
            $mat[$N - 1 - $x][$N - 1 - $y] =
                         $mat[$N - 1 - $y][$x];
 
            // assign temp to left
            $mat[$N - 1 - $y][$x] = $temp;
        }
    }
}
 
// Function to
// print the matrix
function displayMatrix(&$mat)
{
    global $N;
    for ($i = 0; $i < $N; $i++)
    {
        for ($j = 0; $j < $N; $j++)
            echo $mat[$i][$j] . " ";
 
        echo "\n";
    }
    echo "\n";
}
 
// Driver code
 
$mat =  array(array(1, 2, 3, 4),
              array(5, 6, 7, 8),
              array(9, 10, 11, 12),
              array(13, 14, 15, 16));
 
// Function call
rotateMatrix($mat);
 
// Print rotated matrix
displayMatrix($mat);
 
// This code is contributed
// by ChitraNayal
?>


Output

4 8 12 16 
3 7 11 15 
2 6 10 14 
1 5 9 13 

Time Complexity: O(N2), where n is the side of the array. A single traversal of the matrix is needed.
Auxiliary Space: O(1). As a constant space is needed

Example no 2 – Inplace rotate square matrix by 90 degrees by transposing and reversing the matrix:

Follow the given steps to solve the problem:

Below is the implementation of the above approach:

C++




// C++ program to rotate a matrix
// by 90 degrees
#include <bits/stdc++.h>
using namespace std;
#define N 4
 
// An Inplace function to
// rotate a N x N matrix
// by 90 degrees in
// anti-clockwise direction
void rotateMatrix(int mat[][N])
{ // REVERSE every row
    for (int i = 0; i < N; i++)
        reverse(mat[i], mat[i] + N);
 
    // Performing Transpose
    for (int i = 0; i < N; i++) {
        for (int j = i; j < N; j++)
            swap(mat[i][j], mat[j][i]);
    }
}
 
// Function to print the matrix
void displayMatrix(int mat[N][N])
{
    for (int i = 0; i < N; i++) {
        for (int j = 0; j < N; j++) {
            cout << mat[i][j] << " ";
        }
        cout << endl;
    }
    cout << endl;
}
 
/* Driver code */
int main()
{
    int mat[N][N] = { { 1, 2, 3, 4 },
                      { 5, 6, 7, 8 },
                      { 9, 10, 11, 12 },
                      { 13, 14, 15, 16 } };
 
    // Function call
    rotateMatrix(mat);
 
    // Print rotated matrix
    displayMatrix(mat);
 
    return 0;
}


Java




// Java program to rotate a
// matrix by 90 degrees
import java.io.*;
 
class GFG {
 
    // Function to reverse
    // the given 2D arr[][]
    static void Reverse(int i, int mat[][], int N)
    {
        // Initialise start and end index
        int start = 0;
        int end = N - 1;
 
        // Till start < end, swap the element
        // at start and end index
        while (start < end) {
 
            // Swap the element
            int temp = mat[i][start];
            mat[i][start] = mat[i][end];
            mat[i][end] = temp;
 
            // Increment start and decrement
            // end for next pair of swapping
            start++;
            end--;
        }
    }
 
    // An Inplace function to
    // rotate a N x N matrix
    // by 90 degrees in
    // anti-clockwise direction
 
    static void rotateMatrix(int N, int mat[][])
    { // REVERSE every row
        for (int i = 0; i < N; i++)
            Reverse(i, mat, N);
 
        // Performing Transpose
        for (int i = 0; i < N; i++) {
            for (int j = i; j < N; j++) {
                int temp = mat[i][j];
                mat[i][j] = mat[j][i];
                mat[j][i] = temp;
            }
        }
    }
 
    // Function to print the matrix
    static void displayMatrix(int N, int mat[][])
    {
        for (int i = 0; i < N; i++) {
            for (int j = 0; j < N; j++)
                System.out.print(" " + mat[i][j]);
 
            System.out.print("\n");
        }
        System.out.print("\n");
    }
 
    /* Driver code*/
    public static void main(String[] args)
    {
        int N = 4;
 
        int mat[][] = { { 1, 2, 3, 4 },
                        { 5, 6, 7, 8 },
                        { 9, 10, 11, 12 },
                        { 13, 14, 15, 16 } };
 
        // Function call
        rotateMatrix(N, mat);
 
        // Print rotated matrix
        displayMatrix(N, mat);
    }
}
 
// This code is contributed by Aarti_Rathi


Python3




# Python program to rotate
# a matrix by 90 degrees
 
 
def rotateMatrix(mat):
 
    # reversing the matrix
    for i in range(len(mat)):
        mat[i].reverse()
 
    # make transpose of the matrix
    for i in range(len(mat)):
        for j in range(i, len(mat)):
 
            # swapping mat[i][j] and mat[j][i]
            mat[i][j], mat[j][i] = mat[j][i], mat[i][j]
 
 
# Function to print the matrix
def displayMatrix(mat):
 
    for i in range(0, len(mat)):
        for j in range(0, len(mat)):
            print(mat[i][j], end=' ')
        print()
 
 
# Driver code
if __name__ == "__main__":
    mat = [[1, 2, 3, 4],
           [5, 6, 7, 8],
           [9, 10, 11, 12],
           [13, 14, 15, 16]]
 
    # Function call
    rotateMatrix(mat)
 
    # Print rotated matrix
    displayMatrix(mat)
 
# This code is contributed by shivambhagat02(CC).


C#




// C# program to rotate a
// matrix by 90 degrees
using System;
 
class GFG {
    // Reverse each row of matrix
    static void reverse(int N, int[, ] mat)
    {
        // Traverse each row of [,]mat
        for (int i = 0; i < N; i++) {
 
            // Initialise start and end index
            int start = 0;
            int end = N - 1;
 
            // Till start < end, swap the element
            // at start and end index
            while (start < end) {
 
                // Swap the element
                int temp = mat[i, start];
                mat[i, start] = mat[i, end];
                mat[i, end] = temp;
 
                // Increment start and decrement
                // end for next pair of swapping
                start++;
                end--;
            }
        }
    }
    // An Inplace function to
    // rotate a N x N matrix
    // by 90 degrees in anti-
    // clockwise direction
    static void rotateMatrix(int N, int[, ] mat)
    {
        reverse(N, mat);
 
        // Performing Transpose
        for (int i = 0; i < N; i++) {
            for (int j = i; j < N; j++) {
                int temp = mat[i, j];
                mat[i, j] = mat[j, i];
                mat[j, i] = temp;
            }
        }
    }
 
    // Function to print the matrix
    static void displayMatrix(int N, int[, ] mat)
    {
        for (int i = 0; i < N; i++) {
            for (int j = 0; j < N; j++)
                Console.Write(mat[i, j] + " ");
            Console.Write("\n");
        }
    }
 
    // Driver Code
    static public void Main()
    {
        int N = 4;
 
        int[, ] mat = { { 1, 2, 3, 4 },
                        { 5, 6, 7, 8 },
                        { 9, 10, 11, 12 },
                        { 13, 14, 15, 16 } };
 
        // Function call
        rotateMatrix(N, mat);
 
        // Print rotated matrix
        displayMatrix(N, mat);
    }
}
 
// This code is contributed by Aarti_Rathi


Javascript




<script>
 
// JavaScript program to rotate
// a matrix by 90 degrees
function rotateMatrix(mat){
 
    // reversing the matrix
    for(let i = 0; i < mat.length; i++){
        mat[i].reverse()
    }
     
    // make transpose of the matrix
    for(let i = 0; i < mat.length; i++){
        for(let j = i; j < mat.length; j++){
 
            // swapping mat[i][j] and mat[j][i]
            let temp = mat[i][j]
            mat[i][j] = mat[j][i]
            mat[j][i] = temp
        }
    }
}
 
// Function to print the matrix
function displayMatrix(mat){
 
    for(let i = 0; i < mat.length; i++){
        for(let j = 0; j < mat.length; j++){
            document.write(mat[i][j],' ')
        }
        document.write("</br>")
    }
}
 
 
let mat = [[1, 2, 3, 4],
    [5, 6, 7, 8],
    [9, 10, 11, 12],
    [13, 14, 15, 16]]
 
rotateMatrix(mat)
 
// Print rotated matrix
displayMatrix(mat)
 
// This code is contributed by shinjanpatra
 
</script>


Output

4 8 12 16 
3 7 11 15 
2 6 10 14 
1 5 9 13 

Time Complexity: O(N2) + O(N2)  where N is the size of the array.
Auxiliary Space: O(1). As a constant space is needed

Example no 3 – Implementation by using Vectors in c++

Input - Matrix

1 2 3
4 5 6
7 8 9

Algorithmic steps for implementation –

the algorithmic steps to in-place rotate a square matrix by 90 degrees:

  1. Transpose the matrix: For each element matrix[i][j] where i < j, swap it with the element matrix[j][i].
  2. Reverse each row of the matrix: For each row i of the matrix, reverse the order of the elements by swapping matrix[i][j] with matrix[i][n – j – 1] where n is the number of columns in the matrix.
  3. The matrix is now rotated by 90 degrees in place.

Note: The first step transforms the matrix into its transposed form, and the second step reverses the elements in each row, resulting in a rotation of the matrix by 90 degrees.

 Program –

C++




#include <iostream>
#include <vector>
 
using namespace std;
 
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 each column
  for (int i = 0; i < n; i++) {
    for (int j = 0; j < n / 2; j++) {
      swap(matrix[j][i], matrix[n - j - 1][i]);
    }
  }
}
 
int main() {
  vector<vector<int>> matrix = {{1, 2, 3}, {4, 5, 6}, {7, 8, 9}};
  rotateMatrix(matrix);
 
  for (int i = 0; i < matrix.size(); i++) {
    for (int j = 0; j < matrix[0].size(); j++) {
      cout << matrix[i][j] << " ";
    }
    cout << endl;
  }
 
  return 0;
}


Java




public class RotateMatrix {
    public static void rotateMatrix(int[][] matrix)
    {
        int n = matrix.length;
 
        // transpose the matrix
        for (int i = 0; i < n; i++) {
            for (int j = i; j < n; j++) {
                swap(matrix, i, j, j, i);
            }
        }
 
        // reverse each column
        for (int i = 0; i < n; i++) {
            for (int j = 0; j < n / 2; j++) {
                swap(matrix, j, i, n - j - 1, i);
            }
        }
    }
 
    private static void swap(int[][] matrix, int i, int j,
                             int k, int l)
    {
        int temp = matrix[i][j];
        matrix[i][j] = matrix[k][l];
        matrix[k][l] = temp;
    }
    // driver program
    public static void main(String[] args)
    {
        int[][] matrix
            = { { 1, 2, 3 }, { 4, 5, 6 }, { 7, 8, 9 } };
        rotateMatrix(matrix);
 
        for (int i = 0; i < matrix.length; i++) {
            for (int j = 0; j < matrix[0].length; j++) {
                System.out.print(matrix[i][j] + " ");
            }
            System.out.println();
        }
    }
}


Python3




# Python program for the above approach
def rotateMatrix(matrix):
    n = len(matrix)
     
    # transpose the matrix
    for i in range(n):
        for j in range(i,n):
            temp = matrix[i][j]
            matrix[i][j] = matrix[j][i]
            matrix[j][i] = temp
         
    # reverse each column
    for i in range(n):
        for j in range (int(n/2)):
            temp = matrix[n-j-1][i]
            matrix[n-j-1][i] = matrix[j][i]
            matrix[j][i] = temp
         
# driver program
matrix = [[1, 2, 3], [4, 5, 6], [7, 8, 9]]
rotateMatrix(matrix)
for i in range(len(matrix)):
    for j in range(len(matrix[0])):
        print(matrix[i][j], end=" ")
    print("")
     
    # THIS CODE IS CONTRIBUTED BY YASH AGARWAL(YASHAGARWAL23121999)


C#




using System;
using System.Collections.Generic;
 
class Gfg
{
  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 each column
    for (int i = 0; i < n; i++)
    {
      for (int j = 0; j < n / 2; j++)
      {
        int temp = matrix[j][i];
        matrix[j][i] = matrix[n - j - 1][i];
        matrix[n - j - 1][i] = temp;
      }
    }
  }
 
  static void Main(string[] args)
  {
    List<List<int>> matrix = new List<List<int>> { new List<int> { 1, 2, 3 }, new List<int> { 4, 5, 6 }, new List<int> { 7, 8, 9 } };
    RotateMatrix(matrix);
 
    for (int i = 0; i < matrix.Count; i++)
    {
      for (int j = 0; j < matrix[0].Count; j++)
      {
        Console.Write(matrix[i][j] + " ");
      }
      Console.WriteLine();
    }
 
    Console.ReadLine();
  }
}


Javascript




// JavaScript program for the above approach
function rotateMatrix(matrix){
    let n = matrix.length;
     
    // transpose the matrix
    for(let i = 0; i<n; i++){
        for(let j = i; j<n; j++){
            let temp = matrix[i][j];
            matrix[i][j] = matrix[j][i];
            matrix[j][i] = temp;
        }
    }
     
    // reverse each column
    for(let i = 0; i<n; i++){
        for(let j = 0; j<n/2; j++){
            temp = matrix[n - j - 1][i];
            matrix[n - j - 1][i] = matrix[j][i];
            matrix[j][i] = temp;
        }
    }
}
 
 
// driver program
let matrix = [[1, 2, 3], [4, 5, 6], [7, 8, 9]];
rotateMatrix(matrix);
for(let i = 0; i<matrix.length; i++){
    for(let j = 0; j<matrix[0].length; j++){
        console.log(matrix[i][j] + " ");
    }
    console.log("<br>");
}
 
// THIS CODE IS CONTRIBUTED BY YASH AGARWAL(YASHAGAWRAL2852002)


Output

3 6 9 
2 5 8 
1 4 7 

Explanation –

  • In this implementation, the rotateMatrix function takes a 2D vector matrix as input and rotates the matrix by 90 degrees in the anticlockwise direction in place.
    The first step is to transpose the matrix, which is done by swapping the elements matrix[i][j] and matrix[j][i] for i < j.
    The second step is to reverse each column of the matrix, which is done by swapping the elements matrix[j][i] and matrix[n – j – 1][i] where n is the number of rows in the matrix.
  • The time complexity of this algorithm is O(n^2), where n is the number of rows (and columns) in the matrix. This is because the algorithm performs a constant amount of work for each element in the matrix.
  • The Auxiliary Space needed for this algorithm is O(1), since no extra space is used.

Exercise: Turn the 2D matrix by 90 degrees in a clockwise direction without using extra space.
Rotate a matrix by 90 degrees without using any extra space | Set 2

This article is contributed by Aditya Goel.  



Similar Reads

Python3 Program to Inplace rotate square matrix by 90 degrees | Set 1
Given a square matrix, turn it by 90 degrees in anti-clockwise direction without using any extra space.Examples : Input: Matrix: 1 2 3 4 5 6 7 8 9 Output: 3 6 9 2 5 8 1 4 7 The given matrix is rotated by 90 degree in anti-clockwise direction. 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 The given matr
5 min read
Javascript Program to Inplace rotate square matrix by 90 degrees | Set 1
Given a square matrix, turn it by 90 degrees in anti-clockwise direction without using any extra space.Examples : Input: Matrix: 1 2 3 4 5 6 7 8 9 Output: 3 6 9 2 5 8 1 4 7 The given matrix is rotated by 90 degree in anti-clockwise direction. 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 The given matr
5 min read
Rotate matrix by 45 degrees
Given a matrix mat[][] of size N*N, the task is to rotate the matrix by 45 degrees and print the matrix. Examples: Input: N = 6, mat[][] = {{3, 4, 5, 1, 5, 9, 5}, {6, 9, 8, 7, 2, 5, 2}, {1, 5, 9, 7, 5, 3, 2}, {4, 7, 8, 9, 3, 5, 2}, {4, 5, 2, 9, 5, 6, 2}, {4, 5, 7, 2, 9, 8, 3}}Output: 3 6 4 1 9 5 4 5 8 1 4 7 9 7 54 5 8 7 2 9 5 2 9 5 5 7 9 3 3 2 5 5
15+ min read
Rotate all Matrix elements except the diagonal K times by 90 degrees in clockwise direction
Given a square matrix mat[][] of dimension N and an integer K, the task is to rotate the matrix by 90 degrees K times without changing the position of the diagonal elements. Examples: Input: mat[][] = {{1, 2, 3, 4, 5}, {6, 7, 8, 9, 10}, {11, 12, 13, 14, 15}, {16, 17, 18, 19, 20}, {21, 22, 23, 24, 25}}, K = 1Output: 1 16 11 6 5 22 7 12 9 2 23 18 13
10 min read
Python3 Program to Rotate all Matrix elements except the diagonal K times by 90 degrees in clockwise direction
Given a square matrix mat[][] of dimension N and an integer K, the task is to rotate the matrix by 90 degrees K times without changing the position of the diagonal elements. Examples: Input: mat[][] = {{1, 2, 3, 4, 5}, {6, 7, 8, 9, 10}, {11, 12, 13, 14, 15}, {16, 17, 18, 19, 20}, {21, 22, 23, 24, 25}}, K = 1Output: 1 16 11 6 5   22 7 12 9 2 23 18 1
4 min read
Python3 Program for Rotate matrix by 45 degrees
Given a matrix mat[][] of size N*N, the task is to rotate the matrix by 45 degrees and print the matrix. Examples: Input: N = 6, mat[][] = {{3, 4, 5, 1, 5, 9, 5}, {6, 9, 8, 7, 2, 5, 2}, {1, 5, 9, 7, 5, 3, 2}, {4, 7, 8, 9, 3, 5, 2}, {4, 5, 2, 9, 5, 6, 2}, {4, 5, 7, 2, 9, 8, 3}}Output: 3 6 4 1 9 5 4 5 8 1 4 7 9 7 54 5 8 7 2 9 5 2 9 5 5 7 9 3 3 2 5 5
3 min read
Inplace (Fixed space) M x N size matrix transpose
Given an M x N matrix, transpose the matrix without auxiliary memory.It is easy to transpose matrix using an auxiliary array. If the matrix is symmetric in size, we can transpose the matrix inplace by mirroring the 2D array across it's diagonal (try yourself). How to transpose an arbitrary size matrix inplace? See the following matrix, a b c a d g
15+ min read
Rotate a matrix by 90 degree without using any extra space | Set 2
Given a square matrix, turn it by 90 degrees in anti-clockwise direction without using any extra space. Examples: Input: 1 2 3 4 5 6 7 8 9Output: 3 6 9 2 5 8 1 4 7 Rotated the input matrix by90 degrees in anti-clockwise direction.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 13Rotated the input matrix by9
15+ min read
Rotate a Matrix by 180 degree
Given a square matrix, the task is that we turn it by 180 degrees in an anti-clockwise direction without using any extra space. Examples : Input : 1 2 3 4 5 6 7 8 9 Output : 9 8 7 6 5 4 3 2 1 Input : 1 2 3 4 5 6 7 8 9 0 1 2 3 4 5 6 Output : 6 5 4 3 2 1 0 9 8 7 6 5 4 3 2 1 Method: 1 (Only prints rotated matrix) The solution of this problem is that t
15+ min read
Javascript Program for Rotate the matrix right by K times
Given a matrix of size N*M, and a number K. We have to rotate the matrix K times to the right side. Examples: Input : N = 3, M = 3, K = 2 12 23 34 45 56 67 78 89 91 Output : 23 34 12 56 67 45 89 91 78 Input : N = 2, M = 2, K = 2 1 2 3 4 Output : 1 2 3 4 A simple yet effective approach is to consider each row of the matrix as an array and perform an
2 min read
Rotate the matrix right by K times
Given a matrix of size N*M, and a number K. We have to rotate the matrix K times to the right side. Examples: Input : N = 3, M = 3, K = 2 12 23 34 45 56 67 78 89 91 Output : 23 34 12 56 67 45 89 91 78 Input : N = 2, M = 2, K = 2 1 2 3 4 Output : 1 2 3 4 A simple yet effective approach is to consider each row of the matrix as an array and perform an
9 min read
Rotate a matrix by 90 degree in clockwise direction without using any extra space
Given a square matrix, turn it by 90 degrees in a clockwise direction without using any extra space. Examples: Input: 1 2 3 4 5 6 7 8 9 Output: 7 4 1 8 5 2 9 6 3 Input: 1 2 3 4 Output: 3 1 4 2 Method 1 Approach: The approach is similar to Inplace rotate square matrix by 90 degrees | Set 1. The only thing that is different is to print the elements o
15+ min read
Python3 Program to Rotate the matrix right by K times
Given a matrix of size N*M, and a number K. We have to rotate the matrix K times to the right side. Examples: Input : N = 3, M = 3, K = 2 12 23 34 45 56 67 78 89 91 Output : 23 34 12 56 67 45 89 91 78 Input : N = 2, M = 2, K = 2 1 2 3 4 Output : 1 2 3 4 A simple yet effective approach is to consider each row of the matrix as an array and perform an
2 min read
Rotate-matrix module in Python
The rotate-matrix is an interesting new python module, which allows conversion of a matrix(2-D array) into either clockwise rotation or anti-clockwise rotation. It at present consists of only two methods. You can loop through these methods for 'n' number of rotations. Installation This module doesn't come in-built with python but can be installed u
1 min read
Javascript Program for Rotate a Matrix by 180 degree
Given a square matrix, the task is that we turn it by 180 degrees in an anti-clockwise direction without using any extra space.  Examples :  Input : 1 2 3 4 5 6 7 8 9 Output : 9 8 7 6 5 4 3 2 1 Input : 1 2 3 4 5 6 7 8 9 0 1 2 3 4 5 6 Output : 6 5 4 3 2 1 0 9 8 7 6 5 4 3 2 1 Method: 1 (Only prints rotated matrix) The solution of this problem is that
6 min read
Rotate each ring of matrix anticlockwise by K elements
Given a matrix of order M*N and a value K, the task is to rotate each ring of the matrix anticlockwise by K elements. If in any ring elements are less than and equal K then don't rotate it. Examples: Input : k = 3 mat[4][4] = {{1, 2, 3, 4}, {5, 6, 7, 8}, {9, 10, 11, 12}, {13, 14, 15, 16}} Output: 4 8 12 16 3 10 6 15 2 11 7 14 1 5 9 13 Input : k = 2
14 min read
Javascript Program to Rotate Matrix Elements
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 12Recommended: Please solve it on “PRACTICE ” first, before moving on to the solution. The idea is to use loops similar to the program f
5 min read
Rotate Matrix Elements
Given a square matrix, the task is to rotate its elements clockwise by one step. Examples: Input 1 2 3 4 5 6 7 8 9 Output: 4 1 2 7 5 3 8 9 6 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 Approaches to Rotate Matrix Elements:Table of Content Approaches to Rotate Matrix Elements:[Approach 1] Nested Loops
15+ min read
Check if matrix can be converted to another matrix by transposing square sub-matrices
Given two N X M matrices of integers. In an operation, we can transpose any square sub-matrix in matrix1. The task is to check if matrix1 can be converted to matrix2 with the given operation.Examples: Input: matrix1[][] = { {1, 2, 3}, {4, 5, 6}, {7, 8, 9}}, matrix2[][] = { {1, 4, 7}, {2, 5, 6}, {3, 8, 9}} Output: Yes Transpose the whole matrix and
10 min read
Construct a square Matrix whose parity of diagonal sum is same as size of matrix
Given an integer N representing the size of the matrix, the task is to construct a square matrix N * N which have an element from 1 to N2 such that the parity of the sum of its diagonals is equal to the parity of integer N. Examples: Input: N = 4Output:1 2 3 4 8 7 6 59 10 11 1216 15 14 13Explanation:Sum of diagonal = 32 and 36 and integer N = 4, al
6 min read
Construct a graph from given degrees of all vertices
This is a C++ program to generate a graph for a given fixed degree sequence. This algorithm generates a undirected graph for the given degree sequence.It does not include self-edge and multiple edges. Examples: Input : degrees[] = {2, 2, 1, 1} Output : (0) (1) (2) (3) (0) 0 1 1 0 (1) 1 0 0 1 (2) 1 0 0 0 (3) 0 1 0 0 Explanation : We are given that t
7 min read
Finding in and out degrees of all vertices in a graph
Given a directed graph, the task is to count the in and out degree of each vertex of the graph. Examples: Input: Output: Vertex In Out 0 1 2 1 2 1 2 2 3 3 2 2 4 2 2 5 2 2 6 2 1 Approach: Traverse adjacency list for every vertex, if size of the adjacency list of vertex i is x then the out degree for i = x and increment the in degree of every vertex
9 min read
Maximize the sum of products of the degrees between any two vertices of the tree
Given an integer N, the task is to construct a tree such that the sum of [Tex]degree(u) * degree(v) [/Tex]for all ordered pairs (u, v) is the maximum where u != v. Print the maximum possible sum. Examples: Input: N = 4 Output: 26 1 / 2 / 3 / 4 For node 1, 1*2 + 1*2 + 1*1 = 5 For node 2, 2*1 + 2*2 + 2*1 = 8 For node 3, 2*1 + 2*2 + 2*1 = 8 For node 4
6 min read
Detect cycle in the graph using degrees of nodes of graph
Given a graph, the task is to detect a cycle in the graph using degrees of the nodes in the graph and print all the nodes that are involved in any of the cycles. If there is no cycle in the graph then print -1. Examples: Input: Output: 0 1 2 Approach: Recursively remove all vertices of degree 1. This can be done efficiently by storing a map of vert
11 min read
Print nodes having maximum and minimum degrees
Given an undirected graph having N nodes, the task is to print the nodes having minimum and maximum degree.Examples: Input: 1-----2 | | 3-----4 Output: Nodes with maximum degree : 1 2 3 4 Nodes with minimum degree : 1 2 3 4 Every node has a degree of 2. Input: 1 / \ 2 3 / 4 Output: Nodes with maximum degree : 1 2 Nodes with minimum degree : 3 4 App
8 min read
Number of trees whose sum of degrees of all the vertices is L
Given an integer L which is the sum of degrees of all the vertices of some tree. The task is to find the count of all such distinct trees (labeled trees). Two trees are distinct if they have at least a single different edge.Examples: Input: L = 2 Output: 1Input: L = 6 Output: 16 Recommended: Please try your approach on {IDE} first, before moving on
13 min read
Sum of degrees of all nodes of a undirected graph
Given an edge list of a graph we have to find the sum of degree of all nodes of a undirected graph. Example Examples: Input : edge list : (1, 2), (2, 3), (1, 4), (2, 4) Output : sum= 8Brute force approach We will add the degree of each node of the graph and print the sum. C/C++ Code // C++ implementation of above approach #include &lt;bits/stdc++.h
13 min read
Difference Between sum of degrees of odd and even degree nodes in an Undirected Graph
Given an undirected graph with N vertices and M edges, the task is to find the absolute difference Between the sum of degrees of odd degree nodes and even degree nodes in an undirected Graph. Examples: Input: N = 4, edges[][] = { { 1, 2 }, { 1, 3 }, { 1, 4 }, { 2, 3 }, { 2, 4 }, { 3, 4 } } Output: 12 Explanation: Below is the graph for the above in
7 min read
Check whether given degrees of vertices represent a Graph or Tree
Given the number of vertices and the degree of each vertex where vertex numbers are 1, 2, 3,...n. The task is to identify whether it is a graph or a tree. It may be assumed that the graph is Connected. Examples: Input : 5 2 3 1 1 1 Output : Tree Explanation : The input array indicates that vertex one has degree 2, vertex two has degree 3, vertices
5 min read
Count square and non-square numbers before n
Given a number n, we need to count square numbers smaller than or equal to n.Examples : Input : n = 5 Output : Square Number : 2 Non-square numbers : 3 Explanation : Square numbers are 1 and 4. Non square numbers are 2, 3 and 5. Input : n = 10 Output : Square Number : 3 Non-square numbers : 7 Explanation : Square numbers are 1, 4 and 9. Non square
5 min read