一、问题
48、矩阵顺时针旋转90度
54、给你一个 m
行 n
列的矩阵 matrix
,请按照 顺时针螺旋顺序 ,返回矩阵中的所有元素。
题目链接https://leetcode.cn/problems/spiral-matrix/description/
二、旋转矩阵的方法
利用字典类型zip,list(zip(*maxtric)) [ : : -1] 使得矩阵逆时针旋转90度。
顺时针90度:
(1)注意是 matric [ : ]
class Solution:
def rotate(self, matrix: List[List[int]]) -> None:
"""
Do not return anything, modify matrix in-place instead.
"""
matrix[:]=matrix[::-1]
matrix[:]=list(zip(*matrix))
(2)
class Solution:
def rotate(self, matrix: List[List[int]]) -> None:
matrix[:] = [row[::-1] for row in zip(*matrix)]
其中,zip(*maxtric)是把列分别组在一起,list()可以把列组变成行组,现在最左列编程第一行,【::-1】可以使原本的最右列变成第一行。
54、
class Solution:
def spiralOrder(self, matrix: List[List[int]]) -> List[int]:
result = []
while matrix:
result += matrix.pop(0) # 取矩阵第一行并删除
matrix = list(zip(*matrix))[::-1] # 旋转矩阵
return result
三、遍历的方法
不如上面的方法,短小精悍
class Solution:
def spiralOrder(self, matrix: List[List[int]]) -> List[int]:
if not matrix or not matrix[0]:
return list()
rows, columns = len(matrix), len(matrix[0])
order = list()
left, right, top, bottom = 0, columns - 1, 0, rows - 1
while left <= right and top <= bottom:
for column in range(left, right + 1):
order.append(matrix[top][column])
for row in range(top + 1, bottom + 1):
order.append(matrix[row][right])
if left < right and top < bottom:
for column in range(right - 1, left, -1):
order.append(matrix[bottom][column])
for row in range(bottom, top, -1):
order.append(matrix[row][left])
left, right, top, bottom = left + 1, right - 1, top + 1, bottom - 1
return order