Python3實現(xiàn)的旋轉(zhuǎn)矩陣圖像算法示例
本文實例講述了Python3實現(xiàn)的旋轉(zhuǎn)矩陣圖像算法。分享給大家供大家參考,具體如下:
問題:
給定一個 n × n 的二維矩陣表示一個圖像。
將圖像順時針旋轉(zhuǎn) 90 度。
方案一:先按X軸對稱旋轉(zhuǎn), 再用zip()解壓,最后用list重組。
# -*- coding:utf-8 -*-
#! python3
class Solution:
def rotate(self, matrix):
"""
:type matrix: List[List[int]]
:rtype: void Do not return anything, modify matrix in-place instead.
"""
matrix[:] = map(list, zip(*matrix[: : -1]))
return matrix
if __name__ == '__main__':
# 測試代碼
matrix = [
[1,2,3,4],
[5,6,7,8],
[9,10,11,12],
[13,14,15,16]
]
solution = Solution()
result = solution.rotate(matrix)
print(result)
運行結(jié)果:
[[13, 9, 5, 1], [14, 10, 6, 2], [15, 11, 7, 3], [16, 12, 8, 4]]
方案二:找到規(guī)律,用原矩陣數(shù)據(jù) 賦值
# -*- coding:utf-8 -*-
#! python3
class Solution:
def rotate(self, matrix):
"""
:type matrix: List[List[int]]
:rtype: void Do not return anything, modify matrix in-place instead.
"""
m = matrix.copy()
n = len(matrix)
for i in range(n):
matrix[i] = [m[j][i] for j in range(n - 1, -1, -1)]
return
if __name__ == '__main__':
# 測試代碼
matrix = [
[1,2,3,4],
[5,6,7,8],
[9,10,11,12],
[13,14,15,16]
]
solution = Solution()
result = solution.rotate(matrix)
print(result)
運行結(jié)果:
[[13, 9, 5, 1], [14, 10, 6, 2], [15, 11, 7, 3], [16, 12, 8, 4]]
更多關(guān)于Python相關(guān)內(nèi)容感興趣的讀者可查看本站專題:《Python數(shù)學運算技巧總結(jié)》、《Python數(shù)據(jù)結(jié)構(gòu)與算法教程》、《Python函數(shù)使用技巧總結(jié)》、《Python字符串操作技巧匯總》及《Python入門與進階經(jīng)典教程》
希望本文所述對大家Python程序設(shè)計有所幫助。
相關(guān)文章
淺談keras中的keras.utils.to_categorical用法
這篇文章主要介紹了淺談keras中的keras.utils.to_categorical用法,具有很好的參考價值,希望對大家有所幫助。一起跟隨小編過來看看吧2020-07-07
Django對接elasticsearch實現(xiàn)全文檢索的示例代碼
搜索是很常用的功能,如果是千萬級的數(shù)據(jù)應(yīng)該怎么檢索,本文主要介紹了Django對接elasticsearch實現(xiàn)全文檢索的示例代碼,感興趣的可以了解一下2021-08-08

