题目描述:
给定一个 n × n 的二维矩阵表示一个图像,将图像顺时针旋转 90 度。
说明:
你必须在原地旋转图像,这意味着你需要直接修改输入的二维矩阵。请不要使用另一个矩阵来旋转图像。
示例 1:
给定 matrix =
[
[1,2,3],
[4,5,6],
[7,8,9]
],
原地旋转输入矩阵,使其变为:
[
[7,4,1],
[8,5,2],
[9,6,3]
]
示例 2:
给定 matrix =
[
[ 5, 1, 9,11],
[ 2, 4, 8,10],
[13, 3, 6, 7],
[15,14,12,16]
],
原地旋转输入矩阵,使其变为:
[
[15,13, 2, 5],
[14, 3, 4, 1],
[12, 6, 8, 9],
[16, 7,10,11]
]
解题思路1:
按照以下旋转方式,先是淡黄色块,然后是浅蓝色块,依次替换位置
代码1:
def rotate(matrix):
if matrix == [] or matrix[0] == []:
return 0
n = len(matrix)
def get_rotate_xy(i, j):
return (j, n - i - 1)
for i in range(n // 2):
for j in range(i, n - 1 - i):
x, y = get_rotate_xy(i, j)
tmp = matrix[x][y]
matrix[x][y] = matrix[i][j]
while (x, y) != (i, j):
x, y = get_rotate_xy(x, y)
old = matrix[x][y]
matrix[x][y] = tmp
tmp = old
return matrix
matrix = [
[1, 2, 3],
[4, 5, 6],
[7, 8, 9]
]
r = rotate(matrix)
print(r)
结果为:
[[7, 4, 1], [8, 5, 2], [9, 6, 3]]
解题思路2:
1、顺时针转90度可以转换为 先上下翻转,再对角线翻转
2、同理:逆时针转90度可以转换为 先左右翻转,再对角线翻转
for index, row in enumerate(matrix):
print('index=',index, 'row=', row)
结果为:
index= 0 row= [1, 2, 3]
index= 1 row= [4, 5, 6]
index= 2 row= [7, 8, 9]
写法1:
class Solution():
def rotate(self, matrix):
if matrix == [] or matrix[0] == []:
return 0
n = len(matrix) - 1
i = 0
while i < n:
temp = matrix[i]
matrix[i] = matrix[n]
matrix[n] = temp
i += 1
n -= 1
for index, row in enumerate(matrix):
for col in range(index, len(row)): # len(row)
temp = matrix[index][col]
matrix[index][col] = matrix[col][index]
matrix[col][index] = temp
return matrix
s = Solution()
matrix = [
[1, 2, 3],
[4, 5, 6],
[7, 8, 9]
]
r = s.rotate(matrix)
print(r)
写法2:
class Solution(object):
def rotate(self, matrix):
"""
:type matrix: List[List[int]]
:rtype: None Do not return anything, modify matrix in-place instead.
解法:先进行上下翻转,再进行对角翻转
"""
size = len(matrix)
for i in range(size/2):
temp = matrix[i]
matrix[i] = matrix[size-i-1]
matrix[size-i-1] = temp
for index,row in enumerate(matrix):
for col in range(index,len(row)):
temp = matrix[index][col]
matrix[index][col] = matrix[col][index]
matrix[col][index] = temp
结果为:
[[7, 4, 1], [8, 5, 2], [9, 6, 3]]
C++:
class Solution {
public:
void rotate(vector<vector<int>>& matrix) {
// 先进行上下翻转,再进行对角线翻转
int size = matrix.size();
for(int i=0; i<size/2; i++){
matrix[i].swap(matrix[size-i-1]);
}
for(int row=0; row<size; row++){
for(int col=row; col<size; col++){ // 这里用不了swap函数
auto temp = matrix[col][row];
matrix[col][row] = matrix[row][col];
matrix[row][col] = temp;
}
}
}
参考链接:
[1]. leetcode-48–旋转图像
[2]. python之enumerate函数
[3]. LeetCode Medium 48 矩阵旋转 Python
拓展:
来源:CSDN
作者:北木.
链接:https://blog.csdn.net/weixin_43283397/article/details/104551039