Python3实现的旋转矩阵图像算法示例

发布时间:2020-10-20 04:52:10 作者:zhenghaitian
来源:脚本之家 阅读:200

本文实例讲述了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程序设计有所帮助。

推荐阅读:
  1. Python3实现的反转单链表算法示例
  2. Python3最长回文子串算法示例

免责声明:本站发布的内容(图片、视频和文字)以原创、转载和分享为主,文章观点不代表本网站立场,如果涉及侵权请联系站长邮箱:is@yisu.com进行举报,并提供相关证据,一经查实,将立刻删除涉嫌侵权内容。

python3 矩阵 算法

上一篇:使用 Go 管理版本的方法示例

下一篇:android中强制更新app实例代码

相关阅读

您好,登录后才能下订单哦!

密码登录
登录注册
其他方式登录
点击 登录注册 即表示同意《亿速云用户服务条款》