简繁EN

LeetCodeNo. 107

【LeetCode with Python】 48. Rotate Image

目錄

題目

原題頁面:https://leetcode.com/problems/rotate-image/
題目型別:Array
難度評價: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?


分析

順時針90度轉動一個二維矩陣,要求in-place的演算法,也就不是不能另外開一個新的矩陣然後把原矩陣上的元素一個個對應複製過來,而要在原矩陣上進行操作。
目前能想到的有兩種方法。

  1. 第一種比較直觀,首先將原矩陣按照水平軸上下翻轉,然後按照左上到右下的對角線再反轉,則等價於90度順時針轉動。這個方法的缺點是要反轉兩次,優點是直觀,不容易出錯。
  2. 第二種方法每個元素只需要調整一次,但是轉化公式會比較複雜。對於矩陣matrix[n][n]中的某一點matrix[x][y](0<=x, y<n),90度順時針轉動後到了matrix[y][n-x-1],而matrix[y][n-x-1]到了matrix[n-x-1][n-y-1],matrix[n-x-1][n-y-1]到了matrix[n-y-1][x],matrix[n-y-1][x]又到了matrix[x][y],可見這四個點正好實現了一次旋轉互換。

本文采用第二種方法,空間複雜度O(1),時間複雜度O(n*n)。


程式碼

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]

本文地址:https://xnerv.wang/zh-tw/leetcode-rotate-image/