Open In App

Rotate a Matrix by 180 degree

Last Updated : 20 Dec, 2024
Comments
Improve
Suggest changes
Like Article
Like
Report

Given a square matrix, the task is to turn it by 180 degrees. Note that when we rotate a matrix by 180 degree, clockwise and anticlockwise both give same results. 

Examples: 

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

Input: mat[][] = [[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]]

[Naive Approach 1] Rotate 90 Degree Twice – O(n^2) Time and O(1) Space

One simple solution is to use the solutions discussed in Rotate 90 Degree Counterclockwise or Rotate 90 Degree Clockwise two times. These solutions require double effort. We can solve this problem more efficiently by directly finding a relationship between the original matrix and 180 degree rotated matrix.

[Naive Approach 2] Using Auxiliary Matrix – O(n^2) Time and O(n^2) Space

If we take a closer look at the examples, we can notice that after rotation, the first element in the top row moves to the last cell in the last row. Similarly, second element in the top row moves to the second last cell in the last row, and so on. In general, we can notice that mat[i][j] needs to be placed at cell [n-i-1][n-j-1]. So, we can create a new matrix and place all the elements at their correct position. Finally, we copy all the elements from new matrix to the original matrix.

C++
// C++ Code to rotate matrix 180 degree by placing
// elements in new matrix

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

// Function to rotate the matrix by 180 degrees
void rotateMatrix(vector<vector<int>>& mat) {
    int n = mat.size();
  
    // Create an auxiliary matrix
    vector<vector<int>> res(n, vector<int>(n));
  
    // move mat[i][j] to mat[n-i-1][n-j-1]
    for (int i = 0; i < n; i++) {
        for (int j = 0; j < n; j++) {
            res[i][j] = mat[n - i - 1][n - j - 1];
        }
    }
    mat = res;
}

int main() {
    vector<vector<int>> mat = {
        {1, 2, 3},
        {4, 5, 6},
        {7, 8, 9}
    };
    rotateMatrix(mat);
    for (int i = 0; i < mat.size(); i++) {
        for (int j = 0; j < mat[i].size(); j++) {
            cout << mat[i][j] << " ";
        }
        cout << "\n";
    }

    return 0;
}
C
// C Code to rotate matrix 180 degree by placing
// elements in new matrix

#include <stdio.h>

#define N 3

// Function to rotate the matrix by 180 degrees
void rotateMatrix(int mat[N][N]) {
    // Swap elements from the start and end to
    // rotate by 180 degrees
    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][N - j - 1];
            mat[N - i - 1][N - j - 1] = temp;
        }
    }

    // Handle the middle row if the matrix 
    // has odd dimensions
    if (N % 2 != 0) {
        int mid = N / 2;
        for (int j = 0; j < N / 2; j++) {
            int temp = mat[mid][j];
            mat[mid][j] = mat[mid][N - j - 1];
            mat[mid][N - j - 1] = temp;
        }
    }
}

// Driver code
int main() {
    int mat[N][N] = {
        {1, 2, 3},
        {4, 5, 6},
        {7, 8, 9}
    };

    rotateMatrix(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
// Java Code to rotate matrix 180 degree by placing
// elements in new matrix

import java.util.*;

class GfG {

    // Function to rotate the matrix by 180 degrees
    static void rotateMatrix(int[][] mat) {
        int n = mat.length;
        
        // Create an auxiliary matrix
        int[][] res = new int[n][n];

        // Move mat[i][j] to mat[n-i-1][n-j-1]
        for (int i = 0; i < n; i++) {
            for (int j = 0; j < n; j++) {
                res[i][j] = mat[n - i - 1][n - j - 1];
            }
        }

        // Copy result back to the original matrix
        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}
        };

        rotateMatrix(mat);

        // Print the rotated matrix
        for (int[] row : mat) {
            for (int x : row) {
                System.out.print(x + " ");
            }
            System.out.println();
        }
    }
}
Python
# Python Code to rotate matrix 180 degree by placing
# elements in new matrix

# Function to rotate the matrix by 180 degrees
def rotateMatrix(mat):
    n = len(mat)
  
    # Create an auxiliary matrix
    res = [[0] * n for _ in range(n)]
  
    # Move mat[i][j] to mat[n-i-1][n-j-1]
    for i in range(n):
        for j in range(n):
            res[i][j] = mat[n - i - 1][n - j - 1]
    
    # Copy result back to original matrix
    for i in range(n):
        for j in range(n):
            mat[i][j] = res[i][j]

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

    rotateMatrix(mat)

    # Print the rotated matrix
    for row in mat:
        print(" ".join(map(str, row)))
C#
// C# Code to rotate matrix 180 degree by placing
// elements in new matrix

using System;

class GfG {

    // Function to rotate the matrix by 180 degrees
    static void rotateMatrix(int[][] mat) {
        int n = mat.Length;
        int[][] res = new int[n][];  // Create an auxiliary matrix
        for (int i = 0; i < n; i++) {
            res[i] = new int[n];
        }

        // Move mat[i][j] to mat[n-i-1][n-j-1]
        for (int i = 0; i < n; i++) {
            for (int j = 0; j < n; j++) {
                res[i][j] = mat[n - i - 1][n - j - 1];
            }
        }

        // Copy result back to original matrix
        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},
            new int[] {4, 5, 6},
            new int[] {7, 8, 9}
        };

        rotateMatrix(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
// JavaScript Code to rotate matrix 180 degree by placing
// elements in new matrix

// Function to rotate the matrix by 180 degrees
function rotateMatrix(mat) {
    const n = mat.length;

    // Create an auxiliary matrix
    const res = Array.from({ length: n }, () => Array(n).fill(0));

    // Move mat[i][j] to mat[n-i-1][n-j-1]
    for (let i = 0; i < n; i++) {
        for (let j = 0; j < n; j++) {
            res[i][j] = mat[n - i - 1][n - j - 1];
        }
    }

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

// Driver code
const mat = [
    [1, 2, 3],
    [4, 5, 6],
    [7, 8, 9]
];

rotateMatrix(mat);

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

Output
9 8 7 
6 5 4 
3 2 1 

[Expected Approach] In-Place Swapping – O(n^2) Time and O(1) Space

In the above approach, we are placing mat[i][j] at cell [n-i-1][n-j-1]. However, instead of placing mat[i][j] at cell [n-i-1][n-j-1] in a new matrix, we can observe that mat[n-i-1][n-j-1] is also being placed back at mat[i][j]. So, rather than performing this in two separate matrices, we can handle it in same matrix by simply swapping mat[i][j] and mat[n-i-1][n-j-1].

If the matrix has an odd number of rows, the middle row won’t have an opposite to swap with, so we need to handle it separately. This middle row elements have to be reversed among themselves.

rotate_a_matrix_by_180_degee

Rotate a matrix 180 degree by in-place swapping


C++
// C++ Code to rotate matrix 180 degree by swapping
// elements in-place

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

// Function to rotate the matrix by 180 degrees
void rotateMatrix(vector<vector<int>>& mat) {
    int n = mat.size();
  
    // Swap elements from the start and end to
    // rotate by 180 degrees
    for (int i = 0; i < n / 2; i++) {
        for (int j = 0; j < n; j++) {
            swap(mat[i][j], mat[n - i - 1][n - j - 1]);
        }
    }
  
    // Handle the middle row if the matrix 
    // has odd dimensions
    if (n % 2 != 0) {
        int mid = n / 2;
        for (int j = 0; j < n/2; j++)
            swap(mat[mid][j], mat[mid][n - j - 1]);
    }
}

int main() {
    vector<vector<int>> mat = {
        {1, 2, 3},
        {4, 5, 6},
        {7, 8, 9}
    };
    rotateMatrix(mat);
    for (int i = 0; i < mat.size(); i++) {
        for (int j = 0; j < mat[i].size(); j++) {
            cout << mat[i][j] << " ";
        }
        cout << "\n";
    }

    return 0;
}
C
// C Code to rotate matrix 180 degree by swapping
// elements in-place

#include <stdio.h>

#define N 3

// Function to rotate the matrix by 180 degrees
void rotateMatrix(int mat[N][N]) {
  
    // Swap elements from the start and end to
    // rotate by 180 degrees
    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][N - j - 1];
            mat[N - i - 1][N - j - 1] = temp;
        }
    }

    // Handle the middle row if the matrix 
    // has odd dimensions
    if (N % 2 != 0) {
        int mid = N / 2;
        for (int j = 0; j < N / 2; j++) {
            int temp = mat[mid][j];
            mat[mid][j] = mat[mid][N - j - 1];
            mat[mid][N - j - 1] = temp;
        }
    }
}

int main() {
    int mat[N][N] = {
        {1, 2, 3},
        {4, 5, 6},
        {7, 8, 9}
    };

    rotateMatrix(mat);

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

    return 0;
}
Java
// Java Code to rotate matrix 180 degree by swapping
// elements in-place

import java.util.*;

class GfG {

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

        // Swap elements from the start and end to
        // rotate by 180 degrees
        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][n - j - 1];
                mat[n - i - 1][n - j - 1] = temp;
            }
        }

        // Handle the middle row if the matrix 
        // has odd dimensions
        if (n % 2 != 0) {
            int mid = n / 2;
            for (int j = 0; j < n / 2; j++) {
                int temp = mat[mid][j];
                mat[mid][j] = mat[mid][n - j - 1];
                mat[mid][n - j - 1] = temp;
            }
        }
    }

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

        rotateMatrix(mat);

        // Print the rotated matrix
        for (int[] row : mat) {
            for (int x : row) {
                System.out.print(x + " ");
            }
            System.out.println();
        }
    }
}
Python
# Python Code to rotate matrix 180 degree by swapping
# elements in-place

# Function to rotate the matrix by 180 degrees
def rotateMatrix(mat):
    n = len(mat)

    # Swap elements from the start and end to
    # rotate by 180 degrees
    for i in range(n // 2):
        for j in range(n):
            mat[i][j], mat[n - i - 1][n - j - 1] = mat[n - i - 1][n - j - 1], mat[i][j]

    # Handle the middle row if the matrix 
    # has odd dimensions
    if n % 2 != 0:
        mid = n // 2
        for j in range(n // 2):
            mat[mid][j], mat[mid][n - j - 1] = mat[mid][n - j - 1], mat[mid][j]

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

    rotateMatrix(mat)

    # Print the rotated matrix
    for row in mat:
        print(" ".join(map(str, row)))
C#
// C# Code to rotate matrix 180 degree by swapping
// elements in-place

using System;

class GfG {

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

        // Swap elements from the start and end to
        // rotate by 180 degrees
        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][n - j - 1];
                mat[n - i - 1][n - j - 1] = temp;
            }
        }

        // Handle the middle row if the matrix 
        // has odd dimensions
        if (n % 2 != 0) {
            int mid = n / 2;
            for (int j = 0; j < n / 2; j++) {
                int temp = mat[mid][j];
                mat[mid][j] = mat[mid][n - j - 1];
                mat[mid][n - j - 1] = temp;
            }
        }
    }

    static void Main() {
        int[][] mat = {
            new int[] {1, 2, 3},
            new int[] {4, 5, 6},
            new int[] {7, 8, 9}
        };

        rotateMatrix(mat);

        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
// JavaScript Code to rotate matrix 180 degree by swapping
// elements in-place

// Function to rotate the matrix by 180 degrees
function rotateMatrix(mat) {
    const n = mat.length;

    // Swap elements from the start and end to
    // rotate by 180 degrees
    for (let i = 0; i < n / 2; i++) {
        for (let j = 0; j < n; j++) {
            [mat[i][j], mat[n - i - 1][n - j - 1]] = 
            			[mat[n - i - 1][n - j - 1], mat[i][j]];
        }
    }

    // Handle the middle row if the matrix 
    // has odd dimensions
    if (n % 2 !== 0) {
        const mid = Math.floor(n / 2);
        for (let j = 0; j < n / 2; j++) {
            [mat[mid][j], mat[mid][n - j - 1]] = [mat[mid][n - j - 1], mat[mid][j]];
        }
    }
}

// Driver code
const mat = [
    [1, 2, 3],
    [4, 5, 6],
    [7, 8, 9]
];

rotateMatrix(mat);

mat.forEach(row => console.log(row.join(" ")));

Output
9 8 7 
6 5 4 
3 2 1 




Next Article
Article Tags :
Practice Tags :

Similar Reads

  翻译: