Posts Rotate Image
Post
Cancel

Rotate Image

This question is part of NeetCode150 series.

Problem Description

You are given an n x n 2D matrix representing an image, rotate the image by 90 degrees (clockwise).

You have to rotate the image in-place, which means you have to modify the input 2D matrix directly. DO NOT allocate another 2D matrix and do the rotation.

leetcode

Solution

This problem can be solve by taking the transpose of the given matrix and then reversing each row one by one (reflection of the matrix).

Transpose of a Matrix

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
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
class Solution {

    public void rotate(int[][] matrix) {

        int n = matrix.length;

        transpose(matrix, n);
        reflect(matrix, n);

    }

    //take either lower triangle and swap with upper triangle (we can do the other way round also)
    public void transpose(int[][] matrix, int n){

        for(int i=0; i<n; i++){
            for(int j=0; j<i; j++){
                int temp = matrix[i][j];
                matrix[i][j] = matrix[j][i];
                matrix[j][i] = temp;
            }
        }

    }

    //loop through each row and use two pointers to swap elemenets from front and back
    public void reflect(int[][] matrix, int n){

        for(int i=0; i<n; i++){

            int l = 0;
            int r = n-1;

            while(l<r){
                int temp = matrix[i][l];
                matrix[i][l] = matrix[i][r];
                matrix[i][r] = temp;

                l++; r--;

            }

        }

    }

}
This post is licensed under CC BY 4.0 by the author.