python实现螺旋矩阵
Python3实现的旋转矩阵图像算法示例本文实例讲述了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程序设计有所帮助。
原文链接:https://blog.csdn.net/zhenghaitian/article/details/80935434