本文基于各个大佬的文章
上点关注下点赞,明天一定更灿烂!
前言
Python基础好像会了又好像没会,所有我直接开始刷leetcode一边抄样例代码一边学习吧。本系列文章用来记录学习中的思考,写给自己看的,也欢迎大家在评论区指导~
您的每一条评论都会让我更有学习的动力。
一、分析题目
二、思路以及代码
好好好,又是矩阵,想让我去死直说
模拟一下顺时针螺旋的过程,无非是【右→下→左→上】循环,那么关键在于如何控制方向和边界。我们可以维护四个指针,分别表示当前遍历的上边界、下边界、左边界、右边界。
- 首先,初始化四个边界,left=0,right=cols-1,top=0,bottom=rows-1
- 然后确定循环条件,那肯定就是left<=right,top<=bottom
- 接着我们到了里面转圈的步骤,也是很难很难的步骤了。把转圈分解成四步:
向右走(上边界):遍历 matrix[top][left] 到 matrix[top][right],将这些元素添加到 result 列表中 然后更新边界
向下走(右边界):遍历 matrix[top][right] 到 matrix[bottom][right],将这些元素添加到 result 列表中 然后更新边界
向左走(下边界):遍历 matrix[bottom][right] 到 matrix[bottom][left],将这些元素添加到 result 列表中 然后更新边界
向上走(左边界):遍历 matrix[bottom][left] 到 matrix[top][left],将这些元素添加到 result 列表中 然后更新边界
class Solution:
def spiralOrder(self,matrix: List[List[int]]) -> List[int]:
# 如果矩阵为空,直接返回空列表
if not matrix:
return []
rows = len(matrix)
cols = len(matrix[0])
result = []
# 初始化边界
left, right = 0, cols - 1
top, bottom = 0, rows - 1
while left <= right and top <= bottom:
# 从左到右 (上边界)
for c in range(left, right + 1):
result.append(matrix[top][c])
top += 1 # 上边界向下移动
# 从上到下 (右边界)
# 检查是否还有未遍历的行
if top <= bottom:
for r in range(top, bottom + 1):
result.append(matrix[r][right])
right -= 1 # 右边界向左移动
# 从右到左 (下边界)
if top <= bottom and left <= right:
for c in range(right, left - 1, -1):
result.append(matrix[bottom][c])
bottom -= 1 # 下边界向上移动
# 从下到上 (左边界)
if top <= bottom and left <= right:
for r in range(bottom, top - 1, -1):
result.append(matrix[r][left])
left += 1 # 左边界向右移动
return result
我勒个豆,这用时有点邪门了吧
三、本题收获
第一次做对矩阵问题
总结
只会打暴力,基础一团糟,明天再学吧老铁,别真学会了。