本文實例講述了Python3實現的旋轉矩陣圖像算法。分享給大家供大家參考,具體如下:
問題:
給定一個 n × n 的二維矩陣表示一個圖像。
將圖像順時針旋轉 90 度。
方案一:先按X軸對稱旋轉, 再用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)
運行結果:
[[13, 9, 5, 1], [14, 10, 6, 2], [15, 11, 7, 3], [16, 12, 8, 4]]
方案二:找到規律,用原矩陣數據 賦值
# -*- 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)
運行結果:
[[13, 9, 5, 1], [14, 10, 6, 2], [15, 11, 7, 3], [16, 12, 8, 4]]
更多關于Python相關內容感興趣的讀者可查看本站專題:《Python數學運算技巧總結》、《Python數據結構與算法教程》、《Python函數使用技巧總結》、《Python字符串操作技巧匯總》及《Python入門與進階經典教程》
希望本文所述對大家Python程序設計有所幫助。
免責聲明:本站發布的內容(圖片、視頻和文字)以原創、轉載和分享為主,文章觀點不代表本網站立場,如果涉及侵權請聯系站長郵箱:is@yisu.com進行舉報,并提供相關證據,一經查實,將立刻刪除涉嫌侵權內容。