简繁EN

LeetCodeNo. 107

[LeetCode with Python] 48. Rotate Image

Contents

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.

  1. 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.
  2. 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
2
3
4
5
6
7
8
9
10
11
class Solution:
# @param matrix, a list of lists of integers
# @return nothing (void), do not return anything, modify matrix in-place instead.
def rotate(self, matrix):
n = len(matrix)
if 1 == n:
return
round = int(n / 2)
for x in range(0, round):
for y in range(x, n - x - 1):
matrix[n - y - 1][x], matrix[n - x - 1][n - y - 1], matrix[y][n - x - 1], matrix[x][y] = matrix[n - x - 1][n - y - 1], matrix[y][n - x - 1], matrix[x][y], matrix[n - y - 1][x]

Article link: https://xnerv.wang/en/leetcode-rotate-image/