Rotate Image LeetCode Solution

Last updated on October 10th, 2024 at 02:12 am

Here, We see Rotate Image LeetCode Solution. This Leetcode problem is done in many programming languages like C++, Java, JavaScript, Python, etc., with different approaches.

List of all LeetCode Solution

Topics

Array, Math, Matrix

Companies

Amazon, Apple, Microsoft

Level of Question

Medium

Rotate Image LeetCode Solution

Rotate Image LeetCode Solution

Problem Statement

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

Rotate Image leetcode ex1
fig-1
Example 1: (fig-1)
Input: matrix = [[1,2,3],[4,5,6],[7,8,9]]
Output: [[7,4,1],[8,5,2],[9,6,3]]
Rotate Image leetcode ex2
fig-2
Example 2: (fig-2)
Input: matrix = [[5,1,9,11],[2,4,8,10],[13,3,6,7],[15,14,12,16]]
Output: [[15,13,2,5],[14,3,4,1],[12,6,8,9],[16,7,10,11]]

1. Rotate Image Leetcode Solution C++

class Solution {
public:
    void rotate(vector<vector<int>>& matrix) {
    int n = matrix.size();
    
    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;
        }
    } 
    for(int i=0; i<n; i++)
    {
        reverse(matrix[i].begin(), matrix[i].end());
    }        
    }
};

2. Rotate Image Leetcode Solution Java

class Solution {
    public void rotate(int[][] matrix) {
        for(int i = 0; i<matrix.length; i++){
            for(int j = i; j<matrix[0].length; j++){
                int temp = 0;
                temp = matrix[i][j];
                matrix[i][j] = matrix[j][i];
                matrix[j][i] = temp;
            }
        }
        for(int i =0 ; i<matrix.length; i++){
            for(int j = 0; j<matrix.length/2; j++){
                int temp = 0;
                temp = matrix[i][j];
                matrix[i][j] = matrix[i][matrix.length-1-j];
                matrix[i][matrix.length-1-j] = temp;
            }
        }        
    }
}

3. Rotate Image Leetcode Solution JavaScript

var rotate = function(matrix) {
    let n = matrix.length, depth = ~~(n / 2)
    for (let i = 0; i < depth; i++) {
        let len = n - 2 * i - 1, opp = n - 1 - i
        for (let j = 0; j < len; j++) {
            let temp = matrix[i][i+j]
            matrix[i][i+j] = matrix[opp-j][i]
            matrix[opp-j][i] = matrix[opp][opp-j]
            matrix[opp][opp-j] = matrix[i+j][opp]
            matrix[i+j][opp] = temp
        }
    }    
};

4. Rotate Image Leetcode Solution Python

class Solution(object):
    def rotate(self, matrix):
        l = 0
        r = len(matrix) -1
        while l < r:
	        matrix[l], matrix[r] = matrix[r], matrix[l]
	        l += 1
	        r -= 1
        for i in range(len(matrix)):
	        for j in range(i):
		        matrix[i][j], matrix[j][i] = matrix[j][i], matrix[i][j]
Scroll to Top