【LeetCode with Python】 Rotate Image

來源:互聯網
上載者:User

標籤:

部落格網域名稱:http://www.xnerv.wang
原標題頁:https://oj.leetcode.com/problems/rotate-image/
題目類型:下標計算
難度評價:★★★
本文地址:http://blog.csdn.net/nerv3x3/article/details/37968757

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的演算法,也就不是不能另外開一個新的矩陣然後把原矩陣上的元素一個個相應複製過來,而要在原矩陣上進行操作。


眼下能想到的有兩種方法。
第一種比較直觀,首先將原矩陣依照水平軸上下翻轉,然後依照左上到右下的對角線再反轉,則等價於90度順時針轉動。這種方法的缺點是要反轉兩次,長處是直觀,不easy出錯。
另外一種方法每一個元素僅僅須要調整一次,可是轉化公式會比較複雜。對於矩陣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)。

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]

著作權聲明:本文部落格原創文章,部落格,未經同意,不得轉載。

【LeetCode with Python】 Rotate Image

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.