算法题 18 像素翻转 牛客网 CC150

匿名 (未验证) 提交于 2019-12-03 00:41:02

算法题 18 像素翻转 牛客网 CC150_P114

题目描述

有一副由NxN矩阵表示的图像,这里每个像素用一个int表示,请编写一个算法,在不占用额外内存空间的情况下(即不使用缓存矩阵),将图像顺时针旋转90度。

给定一个NxN的矩阵,和矩阵的阶数N,请返回旋转后的NxN矩阵,保证N小于等于500,图像元素小于等于256。

测试样例:
[[1,2,3],[4,5,6],[7,8,9]],3
返回:[[7,4,1],[8,5,2],[9,6,3]]

解题代码:

# -*- coding:utf-8 -*- class Transform:     def transformImage(self, mat, n):         # write code here         #layer表示从外围到里面共有多少层         #总共有layer=0,1,2,...,(n+1)//2层          for layer in range(0,(n+1)//2+1):             first=layer             last=n-layer-1             for i in range(first,last):                 offset=i-first                 # 存储上边                 top=mat[first][i]                 # 从左到上                 mat[first][i]=mat[last-offset][first]                 # 从下到左                 mat[last-offset][first]=mat[last][last-offset]                 # 从右到下                 mat[last][last-offset]=mat[i][last]                 # 从上到右                 mat[i][last]=top         return mat

原文:https://www.cnblogs.com/yanmk/p/9317443.html

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!