You are given an n x n 2D matrix representing an image.
Rotate the image by 90 degrees (clockwise).
Follow up:
Rotate the image by 90 degrees (clockwise).
Follow up:
Could you do this in-place?
这题是要定义一个Layer 逐层 交换
AB
CD
temp=A
A=C
C=D
D=B
B=temp
代码如下:
# @param matrix, a list of lists of integers
# @return a list of lists of integers
def rotate(self, matrix):
n=len(matrix)
num=matrix
for layer in range(n/2):
for i in range(layer,n-layer-1):
tmp=num[layer][i]
num[layer][i]=num[n-i-1][layer]
num[n-i-1][layer]=num[n-layer-1][n-i-1]
num[n-layer-1][n-i-1]=num[i][n-layer-1]
num[i][n-layer-1]=tmp
return num
二维矩阵旋转算法
本文介绍了一个用于将n x n的二维矩阵按顺时针方向旋转90度的算法,并提供了具体的实现代码。该算法通过定义一层又一层的矩形边界来逐层交换元素的位置,最终实现了原地旋转。
640

被折叠的 条评论
为什么被折叠?



