Problem
Problem page: https://leetcode.com/problems/rotate-image/
Topics: Array
Difficulty: Medium
You are given an n x n 2D matrix representing an image.
Rotate the image by 90 degrees (clockwise).Follow up:
Could you do this in-place?
Analysis
The goal is to rotate a 2D matrix 90 degrees clockwise in-place. I have to work on the original matrix without allocating a new one and copying the elements over one by one.
I can think of two ways to do this so far.
- The first way is straightforward. Flip the original matrix top to bottom across its horizontal axis, then flip it again across the diagonal from top-left to bottom-right. This is equivalent to a 90-degree clockwise rotation. It takes two flips, but it's intuitive and easy to get right.
- The second way moves each element only once, but the formula is more complicated. Take an element matrix[x][y] in the matrix matrix[n][n] (0<=x, y<n). After a 90-degree clockwise rotation, it moves to matrix[y][n-x-1]. The element at matrix[y][n-x-1] moves to matrix[n-x-1][n-y-1], the one at matrix[n-x-1][n-y-1] moves to matrix[n-y-1][x], and the one at matrix[n-y-1][x] moves back to matrix[x][y].
I use the second method here, which takes O(1) space and O(n*n) time.
Code
1 | class Solution: |
Article link: https://xnerv.wang/en/leetcode-rotate-image/
