48. 旋转图像
给定一个 n × n 的二维矩阵 matrix 表示一个图像。请你将图像顺时针旋转 90 度。
你必须在 原地 旋转图像,这意味着你需要直接修改输入的二维矩阵。请不要 使用另一个矩阵来旋转图像。
思路:按层级进行模拟,如第一层边长为 side,选取前 side-1 个元素,让他们进行旋转,第二层的边长就是 side-2,选取前 side-2-1 个元素,以此类推。
class Solution:
def rotate(self, matrix: List[List[int]]) -> None:
"""
Do not return anything, modify matrix in-place instead.
"""
n = len(matrix)
width = n - 1
for i in range(n//2):
for j in range(i, i+width):
matrix[i][j], matrix[j][n-i-1], matrix[n-i-1][n-j-1], matrix[n-j-1][i] = \
matrix[n-j-1][i], matrix[i][j], matrix[j][n-i-1], matrix[n-i-1][n-j-1]
width -= 2
54. 螺旋矩阵
给你一个 m 行 n 列的矩阵 matrix ,请按照 顺时针螺旋顺序 ,返回矩阵中的所有元素。
思路:按层次进行模拟,记录他的上下左右边界,每次遍历一层,遍历的时候分四种情况
- left<right and top<bottom 代表这一层围成一个矩形,按四个方向分别遍历
- left=right and top<bottom 代表是一列元素,遍历一列添加到结果
- left<right and top=bottom 代表是一行元素,遍历一行添加到结果
- left=right and top=bottom 代表是一个元素,只需要把这一个添加到结果
class Solution:
def spiralOrder(self, matrix: List[List[int]]) -> List[int]:
m, n = len(matrix), len(matrix[0])
left, right, top, bottom = 0, n-1, 0, m-1
res = []
while left<right and top<bottom:
for i in range(left, right): res.append(matrix[top][i])
for i in range(top, bottom): res.append(matrix[i][right])
for i in range(right, left, -1): res.append(matrix[bottom][i])
for i in range(bottom, top, -1): res.append(matrix[i][left])
left, right, top, bottom = left+1, right-1, top+1, bottom-1
if left == right and top < bottom: res.extend(matrix[i][left] for i in range(top, bottom+1))
elif left < right and top == bottom: res.extend(matrix[top][left:right+1])
elif left == right and top == bottom: res.append(matrix[top][left])
return res
498. 对角线遍历
给你一个大小为 m x n 的矩阵 mat ,请以对角线遍历的顺序,用一个数组返回这个矩阵中的所有元素。
思路:按箭头指示方向模拟,如果超出边界,则变换方向,直到到达最右下角的位置,停止模拟
- 向上的话,行-1 列+1,超出边界让 列+1
- 向下的话,行+1 列-1,超出边界让 行+1
class Solution:
def findDiagonalOrder(self, mat: List[List[int]]) -> List[int]:
upward = True
m, n = len(mat), len(mat[0])
i, j = 0, 0
res = []
while i!=m or j!=n:
if 0<=i<m and 0<=j<n:
res.append(mat[i][j])
if upward:
if 0<=i-1<m and 0<=j+1<n:
i -= 1
j += 1
else:
j += 1
upward = False
else:
if 0<=i+1<m and 0<=j-1<n:
i += 1
j -= 1
else:
i += 1
upward = True
return res