Open In App

Rotate an Image 90 Degree Clockwise

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

Given a square matrix mat[][], turn it by 90 degrees in an clockwise direction without using any extra space

Examples: 

Input: mat[][] = {{1, 2, 3},
            {4, 5, 6},
              {7, 8, 9}}
Output: {{7, 4, 1}, 
                {8, 5, 2}, 
                {9, 6, 3}} 

Input: mat[][] = {{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, 4}

[Naive Approach] - O(n^2) Time and O(n^2) Space

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 n = 4 (second example matrix above)

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]. We first move elements in a temporary matrix, then copy the temporary to the original. If we directly copy elements within the matrix, it would cause data loss.

C++
#include <iostream>
#include <vector>
using namespace std;

// Function to rotate the matrix by 90 degrees clockwise
void rotate90(vector<vector<int>>& mat) {
    int n = mat.size();

    // Initialize the result matrix with zeros
    vector<vector<int>> res(n, vector<int>(n));

    // Flip the matrix clockwise using nested loops
    for (int i = 0; i < n; i++) {
        for (int j = 0; j < n; j++) {
            res[j][n - i - 1] = mat[i][j];
        }
    }

    mat = res;
}

int main() {
    vector<vector<int>> mat = {
        {1, 2, 3, 4},
        {5, 6, 7, 8},
        {9, 10, 11, 12},
        {13, 14, 15, 16}
    };
    rotate90(mat);
    for (auto& row : mat) {
        for (int x : row) {
            cout << x << ' ';
        }
        cout << endl;
    }

    return 0;
}
C
#include <stdio.h>

#define N 4

// Function to rotate the matrix by 90 degrees clockwise
void rotate90(int mat[N][N]) {
    int res[N][N] = {0}; 

    // Flip the matrix clockwise using nested loops
    for (int i = 0; i < N; i++) {
        for (int j = 0; j < N; j++) {
            res[j][N - i - 1] = mat[i][j];
        }
    }

    // Copy result back to mat
    for (int i = 0; i < N; i++) {
        for (int j = 0; j < N; j++) {
            mat[i][j] = res[i][j];
        }
    }
}

int main() {
    int mat[N][N] = {
        {1, 2, 3, 4},
        {5, 6, 7, 8},
        {9, 10, 11, 12},
        {13, 14, 15, 16}
    };

    rotate90(mat);

    // Print the rotated matrix
    for (int i = 0; i < N; i++) {
        for (int j = 0; j < N; j++) {
            printf("%d ", mat[i][j]);
        }
        printf("\n");
    }

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

class GfG {

    // Function to rotate the matrix by 90 degrees clockwise
    static void rotate90(int[][] mat) {
        int n = mat.length;

        // Initialize the result matrix with zeros
        int[][] res = new int[n][n];

        // Flip the matrix clockwise using nested loops
        for (int i = 0; i < n; i++) {
            for (int j = 0; j < n; j++) {
                res[j][n - i - 1] = mat[i][j];
            }
        }

        // Copy result back to mat
        for (int i = 0; i < n; i++) {
            System.arraycopy(res[i], 0, mat[i], 0, n);
        }
    }

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

        rotate90(mat);

        // Print the rotated matrix
        for (int[] row : mat) {
            for (int x : row) {
                System.out.print(x + " ");
            }
            System.out.println();
        }
    }
}
Python
# Function to rotate the matrix by 90 degrees clockwise
def rotate90(mat):
    n = len(mat)

    # Initialize the result matrix with zeros
    res = [[0] * n for _ in range(n)]

    # Flip the matrix clockwise using nested loops
    for i in range(n):
        for j in range(n):
            res[j][n - i - 1] = mat[i][j]

    # Update the original matrix with the result
    for i in range(n):
        for j in range(n):
            mat[i][j] = res[i][j]


mat = [
    [1, 2, 3, 4],
    [5, 6, 7, 8],
    [9, 10, 11, 12],
    [13, 14, 15, 16]
]

rotate90(mat)

# Print the rotated matrix
for row in mat:
    print(" ".join(map(str, row)))
C#
using System;

class GfG {

    // Function to rotate the matrix by 90 degrees clockwise
    static void rotate90(int[][] mat) {
        int n = mat.Length;

        // Initialize the result matrix with zeros
        int[][] res = new int[n][];
        for (int i = 0; i < n; i++) {
            res[i] = new int[n];
        }

        // Flip the matrix clockwise using nested loops
        for (int i = 0; i < n; i++) {
            for (int j = 0; j < n; j++) {
                res[j][n - i - 1] = mat[i][j];
            }
        }

        // Copy result back to mat
        for (int i = 0; i < n; i++) {
            Array.Copy(res[i], mat[i], n);
        }
    }

    public static void Main() {
        int[][] mat = {
            new int[] {1, 2, 3, 4},
            new int[] {5, 6, 7, 8},
            new int[] {9, 10, 11, 12},
            new int[] {13, 14, 15, 16}
        };

        rotate90(mat);

        // Print the rotated matrix
        for (int i = 0; i < mat.Length; i++) {
            for (int j = 0; j < mat[i].Length; j++) {
                Console.Write(mat[i][j] + " ");
            }
            Console.WriteLine();
        }
    }
}
JavaScript
// Function to rotate the matrix by 90 degrees clockwise
function rotate90(mat) {
    const n = mat.length;

    // Initialize the result matrix with zeros
    const res = Array.from({ length: n }, () => Array(n).fill(0));

    // Flip the matrix clockwise using nested loops
    for (let i = 0; i < n; i++) {
        for (let j = 0; j < n; j++) {
            res[j][n - i - 1] = mat[i][j];
        }
    }

    // Copy result back to mat
    for (let i = 0; i < n; i++) {
        mat[i] = res[i].slice();
    }
}

const mat = [
    [1, 2, 3, 4],
    [5, 6, 7, 8],
    [9, 10, 11, 12],
    [13, 14, 15, 16]
];

rotate90(mat);

// Print the rotated matrix
mat.forEach(row => {
    console.log(row.join(" "));
});

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

[Expected Approach 1] Forming Cycles - O(n^2) Time and O(1) Space

The approach is similar to Inplace rotate square matrix by 90 degrees counterclockwise. The only thing that is different is to print the elements of the cycle in a clockwise direction i.e. An n x n matrix will have floor(n/2) square cycles.  For example, a 3 X 3 matrix will have 1 cycle and 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. 

For each square cycle, we swap the elements involved with the corresponding cell in the matrix in the clockwise direction. We just need a temporary variable for this.

Explanation:

Let us consider the below matrix for example
 {{1, 2, 3},
{4, 5, 6},
{7, 8, 9}}
During first iteration of first and only cycle 
mat[i][j] = Element at first index (leftmost corner top)= 1.
mat[j][n-1-i]= Rightmost corner top Element = 3.
mat[n-1-i][n-1-j] = Rightmost corner bottom element = 9.
mat[n-1-j][i] = Leftmost corner bottom element = 7.
Move these elements in the clockwise direction. 
During second iteration of first and only cycle
mat[i][j] = 2.
mat[j][n-1-i] = 6.
mat[n-1-i][n-1-j] = 8.
mat[n-1-j][i] = 4. 
Similarly, move these elements in the clockwise direction. 

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
  • Now run a loop in each cycle from i to n - i - 1, loop counter is j
  • The elements in the current group are P1 (i, j), P2 (n-1-j, i), P3 (n-1-i, n-1-j) and P4 (j, n-1-i), now rotate these 4 elements, i.e. temp <- P1, P1 <- P2, P2<- P3, P3<- P4, P4<-temp

Below is the implementation of the above approach:

C++
#include <bits/stdc++.h>
using namespace std;

// Function to rotate a square matrix by 90 degrees in clockwise direction
void rotate90(vector<vector<int>>& mat) {
    int n = mat.size();

    // Consider all cycles one by one
    for (int i = 0; i < n / 2; i++) {

        // Consider elements in group of 4 as P1, P2, P3 & P4 in current square
        for (int j = i; j < n - i - 1; j++) {

            // Swap elements in clockwise order
            int temp = mat[i][j];
            mat[i][j] = mat[n - 1 - j][i];                 // Move P4 to P1
            mat[n - 1 - j][i] = mat[n - 1 - i][n - 1 - j]; // Move P3 to P4
            mat[n - 1 - i][n - 1 - j] = mat[j][n - 1 - i]; // Move P2 to P3
            mat[j][n - 1 - i] = temp;                      // Move P1 to P2
        }
    }
}

int main() {
    vector<vector<int>> mat = {
        {1, 2, 3, 4},
        {5, 6, 7, 8},
        {9, 10, 11, 12},
        {13, 14, 15, 16}
    };
    rotate90(mat);
    for (auto& row : mat) {
        for (int x : row) {
            cout << x << ' ';
        }
        cout << endl;
    }

    return 0;
}
C
#include <stdio.h>

#define N 4

// Function to rotate a square matrix by 90 degrees in clockwise direction
void rotate90(int mat[N][N]) {
    int n = N;

    // Consider all cycles one by one
    for (int i = 0; i < n / 2; i++) {

        // Consider elements in group of 4 as P1, P2, P3 & P4 in current square
        for (int j = i; j < n - i - 1; j++) {

            // Swap elements in clockwise order
            int temp = mat[i][j];
            mat[i][j] = mat[n - 1 - j][i];                 // Move P4 to P1
            mat[n - 1 - j][i] = mat[n - 1 - i][n - 1 - j]; // Move P3 to P4
            mat[n - 1 - i][n - 1 - j] = mat[j][n - 1 - i]; // Move P2 to P3
            mat[j][n - 1 - i] = temp;                      // Move P1 to P2
        }
    }
}

// Driver code
int main() {
    int mat[N][N] = {
        {1, 2, 3, 4},
        {5, 6, 7, 8},
        {9, 10, 11, 12},
        {13, 14, 15, 16}
    };

    rotate90(mat);

    // Print the rotated matrix
    for (int i = 0; i < N; i++) {
        for (int j = 0; j < N; j++) {
            printf("%d ", mat[i][j]);
        }
        printf("\n");
    }

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

class GfG {

    // Function to rotate a square matrix by 90 degrees in clockwise direction
    static void rotate90(int[][] mat) {
        int n = mat.length;

        // Consider all cycles one by one
        for (int i = 0; i < n / 2; i++) {

            // Consider elements in group of 4 as P1, P2, P3 & P4 in current square
            for (int j = i; j < n - i - 1; j++) {

                // Swap elements in clockwise order
                int temp = mat[i][j];
                mat[i][j] = mat[n - 1 - j][i];                 // Move P4 to P1
                mat[n - 1 - j][i] = mat[n - 1 - i][n - 1 - j]; // Move P3 to P4
                mat[n - 1 - i][n - 1 - j] = mat[j][n - 1 - i]; // Move P2 to P3
                mat[j][n - 1 - i] = temp;                      // Move P1 to P2
            }
        }
    }

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

        rotate90(mat);

        // Print the rotated matrix
        for (int[] row : mat) {
            for (int x : row) {
                System.out.print(x + " ");
            }
            System.out.println();
        }
    }
}
Python
# Function to rotate a square matrix by 90 degrees in clockwise direction
def rotate90(mat):
    n = len(mat)

    # Consider all cycles one by one
    for i in range(n // 2):

        # Consider elements in group of 4 as P1, P2, P3 & P4 in current square
        for j in range(i, n - i - 1):

            # Swap elements in clockwise order
            temp = mat[i][j]
            mat[i][j] = mat[n - 1 - j][i]                # Move P4 to P1
            mat[n - 1 - j][i] = mat[n - 1 - i][n - 1 - j]  # Move P3 to P4
            mat[n - 1 - i][n - 1 - j] = mat[j][n - 1 - i]  # Move P2 to P3
            mat[j][n - 1 - i] = temp                      # Move P1 to P2

# Driver code
mat = [
    [1, 2, 3, 4],
    [5, 6, 7, 8],
    [9, 10, 11, 12],
    [13, 14, 15, 16]
]

rotate90(mat)

# Print the rotated matrix
for row in mat:
    print(" ".join(map(str, row)))
C#
using System;

class GfG {

    // Function to rotate a square matrix by 90 degrees in clockwise direction
    static void rotate90(int[][] mat) {
        int n = mat.Length;

        // Consider all cycles one by one
        for (int i = 0; i < n / 2; i++) {

            // Consider elements in group of 4 as P1, P2, P3 & P4 in current square
            for (int j = i; j < n - i - 1; j++) {

                // Swap elements in clockwise order
                int temp = mat[i][j];
                mat[i][j] = mat[n - 1 - j][i];                 // Move P4 to P1
                mat[n - 1 - j][i] = mat[n - 1 - i][n - 1 - j]; // Move P3 to P4
                mat[n - 1 - i][n - 1 - j] = mat[j][n - 1 - i]; // Move P2 to P3
                mat[j][n - 1 - i] = temp;                      // Move P1 to P2
            }
        }
    }

    public static void Main() {
        int[][] mat = {
            new int[] {1, 2, 3, 4},
            new int[] {5, 6, 7, 8},
            new int[] {9, 10, 11, 12},
            new int[] {13, 14, 15, 16}
        };

        rotate90(mat);

        // Print the rotated matrix
        for (int i = 0; i < mat.Length; i++) {
            for (int j = 0; j < mat[i].Length; j++) {
                Console.Write(mat[i][j] + " ");
            }
            Console.WriteLine();
        }
    }
}
JavaScript
// Function to rotate a square matrix by 90 degrees in clockwise direction
function rotate90(mat) {
    const n = mat.length;

    // Consider all cycles one by one
    for (let i = 0; i < n / 2; i++) {

        // Consider elements in group of 4 as P1, P2, P3 & P4 in current square
        for (let j = i; j < n - i - 1; j++) {

            // Swap elements in clockwise order
            let temp = mat[i][j];
            mat[i][j] = mat[n - 1 - j][i];                 // Move P4 to P1
            mat[n - 1 - j][i] = mat[n - 1 - i][n - 1 - j]; // Move P3 to P4
            mat[n - 1 - i][n - 1 - j] = mat[j][n - 1 - i]; // Move P2 to P3
            mat[j][n - 1 - i] = temp;                      // Move P1 to P2
        }
    }
}

// Driver code
const mat = [
    [1, 2, 3, 4],
    [5, 6, 7, 8],
    [9, 10, 11, 12],
    [13, 14, 15, 16]
];

rotate90(mat);

// Print the rotated matrix
mat.forEach(row => console.log(row.join(" ")));

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

[Expected Approach 2] Transposing and Reversing Rows - O(n^2) Time and O(1) Space

When you think about rotating a square 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:

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

Below is the implementation of the above approach:

C++
#include <bits/stdc++.h>
using namespace std;

// Function to rotate a square matrix by 90 
// degrees in clockwise direction
void rotate90(vector<vector<int>> &mat){ 
  	int n = mat.size();
  	
    // Perform Transpose
    for (int i = 0; i < n; i++) {
        for (int j = i + 1; j < n; j++) {
            swap(mat[i][j], mat[j][i]);
        }
    }

    // Reverse each row
    for (int i = 0; i < n; i++)
        reverse(mat[i].begin(), mat[i].end());
}

int main() {
    vector<vector<int>> mat = {
        {1, 2, 3, 4},
        {5, 6, 7, 8},
        {9, 10, 11, 12},
        {13, 14, 15, 16}
    };
    
    rotate90(mat);

    // Print the rotated matrix
    int n = mat.size();
    for (int i = 0; i < n; i++) {
        for (int j = 0; j < n; j++) {
            cout << mat[i][j] << " ";
        }
        cout << endl;
    }

    return 0;
}
C
#include <stdio.h>

#define N 4

// Function to rotate a square matrix by 90 
// degrees in clockwise direction
void rotate90(int mat[N][N]) {
    int n = N;
    
    // Perform Transpose
    for (int i = 0; i < n; i++) {
        for (int j = i + 1; j < n; j++) {
            int temp = mat[i][j];
            mat[i][j] = mat[j][i];
            mat[j][i] = temp;
        }
    }

    // Reverse each row
    for (int i = 0; i < n; i++) {
        int start = 0, end = n - 1;
        while (start < end) {
            int temp = mat[i][start];
            mat[i][start] = mat[i][end];
            mat[i][end] = temp;
            start++;
            end--;
        }
    }
}

// Driver code
int main() {
    int mat[N][N] = {
        {1, 2, 3, 4},
        {5, 6, 7, 8},
        {9, 10, 11, 12},
        {13, 14, 15, 16}
    };

    rotate90(mat);

    // Print the rotated matrix
    for (int i = 0; i < N; i++) {
        for (int j = 0; j < N; j++) {
            printf("%d ", mat[i][j]);
        }
        printf("\n");
    }

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

class GfG {

    // Function to rotate a square matrix by 90 
    // degrees in clockwise direction
    static void rotate90(int[][] mat) {
        int n = mat.length;

        // Perform Transpose
        for (int i = 0; i < n; i++) {
            for (int j = i + 1; j < n; j++) {
                int temp = mat[i][j];
                mat[i][j] = mat[j][i];
                mat[j][i] = temp;
            }
        }

        // Reverse each row
        for (int i = 0; i < n; i++) {
            int start = 0, end = n - 1;
            while (start < end) {
                int temp = mat[i][start];
                mat[i][start] = mat[i][end];
                mat[i][end] = temp;
                start++;
                end--;
            }
        }
    }

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

        rotate90(mat);

        // Print the rotated matrix
        for (int[] row : mat) {
            for (int x : row) {
                System.out.print(x + " ");
            }
            System.out.println();
        }
    }
}
Python
# Function to rotate a square matrix by 90 
# degrees in clockwise direction
def rotate90(mat):
    n = len(mat)

    # Perform Transpose
    for i in range(n):
        for j in range(i + 1, n):
            mat[i][j], mat[j][i] = mat[j][i], mat[i][j]

    # Reverse each row
    for row in mat:
        row.reverse()

# Driver code
mat = [
    [1, 2, 3, 4],
    [5, 6, 7, 8],
    [9, 10, 11, 12],
    [13, 14, 15, 16]
]

rotate90(mat)

# Print the rotated matrix
for row in mat:
    print(" ".join(map(str, row)))
C#
using System;

class GfG {

    // Function to rotate a square matrix by 90 
    // degrees in clockwise direction
    static void rotate90(int[][] mat) {
        int n = mat.Length;

        // Perform Transpose
        for (int i = 0; i < n; i++) {
            for (int j = i + 1; j < n; j++) {
                int temp = mat[i][j];
                mat[i][j] = mat[j][i];
                mat[j][i] = temp;
            }
        }

        // Reverse each row
        for (int i = 0; i < n; i++) {
            Array.Reverse(mat[i]);
        }
    }

    public static void Main() {
        int[][] mat = {
            new int[] {1, 2, 3, 4},
            new int[] {5, 6, 7, 8},
            new int[] {9, 10, 11, 12},
            new int[] {13, 14, 15, 16}
        };

        rotate90(mat);

        // Print the rotated matrix
        for (int i = 0; i < mat.Length; i++) {
            for (int j = 0; j < mat[i].Length; j++) {
                Console.Write(mat[i][j] + " ");
            }
            Console.WriteLine();
        }
    }
}
JavaScript
// Function to rotate a square matrix by 90 
// degrees in clockwise direction
function rotate90(mat) {
    const n = mat.length;

    // Perform Transpose
    for (let i = 0; i < n; i++) {
        for (let j = i + 1; j < n; j++) {
            [mat[i][j], mat[j][i]] = [mat[j][i], mat[i][j]];
        }
    }

    // Reverse each row
    for (let i = 0; i < n; i++) {
        mat[i].reverse();
    }
}

// Driver code
const mat = [
    [1, 2, 3, 4],
    [5, 6, 7, 8],
    [9, 10, 11, 12],
    [13, 14, 15, 16]
];

rotate90(mat);

// Print the rotated matrix
mat.forEach(row => console.log(row.join(" ")));

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

Alternate Implementation

We can alternatively do the following as well. But the above implementation is better as row reversal is more cache friendly than column reversal.

  1. Reverse Individual Columns
  2. Transpose the Matrix
C++
#include <bits/stdc++.h>
using namespace std;

// Function to rotate a square matrix by 90 degrees
// in clockwise direction
void rotate90(vector<vector<int>> &mat){ 
  	int n = mat.size();
  	
  	// Reverse Columns
    for (int i = 0; i < n/2; i++)
    {
        for (int j = 0; j < n; j++)
        {
            swap(mat[i][j], mat[n - i - 1][j]);
        }
    }
        
    // Perform Transpose
    for (int i = 0; i < n; i++) {
        for (int j = i+1; j < n; j++) {
            swap(mat[i][j], mat[j][i]);
        }
    }    

}

int main() {
    vector<vector<int>> mat = {
        {1, 2, 3, 4},
        {5, 6, 7, 8},
        {9, 10, 11, 12},
        {13, 14, 15, 16}
    };
    
    rotate90(mat);

    // Print the rotated matrix
    int n = mat.size();
    for (int i = 0; i < n; i++) {
        for (int j = 0; j < n; j++) {
            cout << mat[i][j] << " ";
        }
        cout << endl;
    }

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

class GfG {
  
    // Function to rotate a square matrix by 90 degrees
  	// in clockwise direction
    static void rotate90(int[][] mat) {
        int n = mat.length;

        // Reverse Columns
        for (int i = 0; i < n/2; i++) {
            for (int j = 0; j < n; j++) {
                int temp = mat[i][j];
                mat[i][j] = mat[n - i - 1][j];
                mat[n - i - 1][j] = temp;
            }
        }

        // Perform Transpose
        for (int i = 0; i < n; i++) {
            for (int j = i+1; j < n; j++) {
                int temp = mat[i][j];
                mat[i][j] = mat[j][i];
                mat[j][i] = temp;
            }
        }
    }

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

        rotate90(mat);

        // Print the rotated matrix
        int n = mat.length;
        for (int i = 0; i < n; i++) {
            for (int j = 0; j < n; j++) {
                System.out.print(mat[i][j] + " ");
            }
            System.out.println();
        }
    }
}
Python
# Function to rotate a square matrix by 90 degrees 
# in clockwise direction
def rotate90(mat):
    n = len(mat)
    
    # Reverse Columns
    for i in range(n // 2):
        for j in range(n):
            mat[i][j], mat[n - i - 1][j] = mat[n - i - 1][j], mat[i][j]
            
    # Perform Transpose
    for i in range(n):
        for j in range(i + 1, n):
            mat[i][j], mat[j][i] = mat[j][i], mat[i][j]


if __name__ == "__main__":
    mat = [
        [1, 2, 3, 4],
        [5, 6, 7, 8],
        [9, 10, 11, 12],
        [13, 14, 15, 16]
    ]
    
    rotate90(mat)

    # Print the rotated matrix
    n = len(mat)
    for i in range(n):
        for j in range(n):
            print(mat[i][j], end=" ")
        print()
C#
using System;

class GfG {
  
    // Function to rotate a square matrix by 90 degrees
  	// in clockwise direction
    static void rotate90(int[][] mat) {
        int n = mat.Length;

        // Reverse Columns
        for (int i = 0; i < n/2; i++) {
            for (int j = 0; j < n; j++) {
                int temp = mat[i][j];
                mat[i][j] = mat[n - i - 1][j];
                mat[n - i - 1][j] = temp;
            }
        }

        // Perform Transpose
        for (int i = 0; i < n; i++) {
            for (int j = i+1; j < n; j++) {
                int temp = mat[i][j];
                mat[i][j] = mat[j][i];
                mat[j][i] = temp;
            }
        }
    }

    static void Main(string[] args) {
        int[][] mat = {
            new int[] {1, 2, 3, 4},
            new int[] {5, 6, 7, 8},
            new int[] {9, 10, 11, 12},
            new int[] {13, 14, 15, 16}
        };

        rotate90(mat);

        // Print the rotated matrix
        int n = mat.Length;
        for (int i = 0; i < n; i++) {
            for (int j = 0; j < n; j++) {
                Console.Write(mat[i][j] + " ");
            }
            Console.WriteLine();
        }
    }
}
JavaScript
// Function to rotate a square matrix by 90 degrees 
// in clockwise direction
function rotate90(mat) {
    let n = mat.length;

    // Reverse Columns
    for (let i = 0; i < n/2; i++) {
        for (let j = 0; j < n; j++) {
            let temp = mat[i][j];
            mat[i][j] = mat[n - i - 1][j];
            mat[n - i - 1][j] = temp;
        }
    }

    // Perform Transpose
    for (let i = 0; i < n; i++) {
        for (let j = i+1; j < n; j++) {
            let temp = mat[i][j];
            mat[i][j] = mat[j][i];
            mat[j][i] = temp;
        }
    }
}

let mat = [
    [1, 2, 3, 4],
    [5, 6, 7, 8],
    [9, 10, 11, 12],
    [13, 14, 15, 16]
];

rotate90(mat);

// Print the rotated matrix
let n = mat.length;
for (let i = 0; i < n; i++) {
    for (let j = 0; j < n; j++) {
        process.stdout.write(mat[i][j] + " ");
    }
    console.log();
}

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



Next Article
Article Tags :
Practice Tags :

Similar Reads