一、73. 矩阵置零
1. 解题思路
1. 使用两个数组分别标记每行每列是否有0,初始化全为False,遇到0就变成True。
2. 遍历矩阵,遇到0就将False改成True。
3. 再次遍历矩阵,更新原数组,将0的行列置为0。
2. 代码实现
class Solution:
def setZeroes(self, matrix: List[List[int]]) -> None:
"""
Do not return anything, modify matrix in-place instead.
"""
m, n = len(matrix), len(matrix[0])
row, col = [False]*m, [False]*n
for i in range(m):
for j in range(n):
if matrix[i][j] == 0:
row[i] = col[j] = True
for i in range(m):
for j in range(n):
if row[i] or col[j]:
matrix[i][j] = 0
二、54.螺旋矩阵
1. 解题思路
(1)判断传入的矩阵是否具备合法性,不合法就直接返回空数组。
(2)定义res空数组,用于存储最终的结果。
(3)定义四个变量,分别是矩阵的四个边界。
2. 代码实现
class Solution:
def spiralOrder(self, matrix: List[List[int]]) -> List[int]:
if not matrix or not matrix[0]:
return []
res = []
left,right = 0, len(matrix[0])-1
top, bottom = 0, len(matrix)-1
while left <= right and top <= bottom:
for i in range(left, right+1):
res.append(matrix[top][i])
for i in range(top+1, bottom+1):
res.append(matrix[i][right])
if left < right and top < bottom:
for i in range(right-1, left, -1):
res.append(matrix[bottom][i])
for i in range(bottom, top, -1):
res.append(matrix[i][left])
left += 1
right -= 1
top += 1
bottom -= 1
return res
三、48.旋转图像
1. 解题思路
(1)使用逐层旋转的方法,由于是n*n的矩阵,所以只需要定义left和right的初始值即可: left, right = 0, len(matrix)。left和right初始值分别直接赋值给top和bottom即可。
(2)定义一个单独的变量topleft,用于存储左上角的数值,方便后面进行交换。
(3)逐层进行旋转,也就是先逐次旋转四个顶点,也就是进行值的交换,然后旋转偏移量为i的元素。
2. 代码实现
class Solution:
def rotate(self, matrix: List[List[int]]) -> None:
left, right = 0, len(matrix)-1
while left < right:
for i in range(right-left):
top, bottom = left, right
topleft = matrix[top][left+i]
matrix[top][left+i] = matrix[bottom-i][left]
matrix[bottom-i][left] = matrix[bottom][right-i]
matrix[bottom][right-i] = matrix[top+i][right]
matrix[top+i][right] = topleft
left+=1
right-=1