Learn DSA
Depth-First Search
Greedy Algorithms
Matrices
Rotate Image
medium
DESCRIPTION (credit Leetcode.com)
Write a function to rotate an n x n 2D matrix representing an image by 90 degrees clockwise. The rotation must be done in-place, meaning you should modify the input matrix directly without using an additional matrix for the operation.
Input:
Output:
Explanation: The matrix is rotated by 90 degrees clockwise, transforming its columns into rows in reverse order.
💻 Desktop Required
The code editor works best on larger screens. Please open this page on your computer to write and run code.
You are given an `n x n` 2D matrix representing an image, return the marix such that image is rotated by 90 degrees (clockwise). For example, given the matrix: ``` [ [1,2,3], [4,5,6], [7,8,9] ] ``` The rotated matrix should be: ``` [ [7,4,1], [8,5,2], [9,6,3] ] ```
Run your code to see results here
Have suggestions or found something wrong?
Explanation
Step 1:
def rotate_image(matrix):n = len(matrix)# Transpose the matrixfor i in range(n):for j in range(i, n):matrix[i][j], matrix[j][i] = \matrix[j][i], matrix[i][j]# Reverse each rowfor i in range(n):matrix[i] = matrix[i][::-1]return matrix
n = 3
0 / 12
Step 2:
def rotate_image(matrix):n = len(matrix)# Transpose the matrixfor i in range(n):for j in range(i, n):matrix[i][j], matrix[j][i] = \matrix[j][i], matrix[i][j]# Reverse each rowfor i in range(n):matrix[i] = matrix[i][::-1]return matrix
swap matrix[2][2] and matrix[2][2]
0 / 4
Solution
def rotate_image(matrix):n = len(matrix)# Transpose the matrixfor i in range(n):for j in range(i, n):matrix[i][j], matrix[j][i] = \matrix[j][i], matrix[i][j]# Reverse each rowfor i in range(n):matrix[i] = matrix[i][::-1]return matrix
rotate image
0 / 17
Complexity Analysis
Login to track your progress
Your account is free and you can post anonymously if you choose.