leetcode hot100 54.螺旋矩阵 medium


计数,计数够了停止

python 复制代码
class Solution:
    def spiralOrder(self, matrix: List[List[int]]) -> List[int]:

        top = 0
        bottom = len(matrix)-1
        left = 0
        right = len(matrix[0])-1

        total = len(matrix) * len(matrix[0])
        cnt = 0 
        res = []

        while cnt < total:
            # 当走到某条边的时候,可能已经遍历完了所有元素,break跳出剩下的 for 循环

            for i in range(left,right+1):  # 左闭右开,不+1遍历不到right
                res.append(matrix[top][i])
                cnt += 1
            
            if cnt >= total: break
            
            top +=1  # 更新上边界

            for i in range(top, bottom+1):
                res.append(matrix[i][right])
                cnt += 1
            if cnt >= total: break
            
            right -=1  # 更新右边界

            for i in range(right, left-1, -1): # 左闭右开,不-1遍历不到left
                res.append(matrix[bottom][i])
                cnt += 1
            if cnt >= total: break
            
            bottom -=1  # 更新下边界

            for i in range(bottom, top-1,-1):
                res.append(matrix[i][left])
                cnt += 1
            if cnt >= total: break
            
            left +=1  # 更新左边界

        return res
        
相关推荐
退休倒计时7 小时前
【每日一题】LeetCode 437. 路径总和 III TypeScript
算法·leetcode·typescript
tachibana28 小时前
hot100 翻转二叉树(226)
java·数据结构·算法·leetcode
兰令水8 小时前
leecodecode【面试150】【2026.7.9打卡-java版本】
java·数据结构·leetcode·面试·职场和发展
Tisfy10 小时前
LeetCode 1288.删除被覆盖区间:排序(非二重循环暴力)
算法·leetcode·题解·排序
知无不研10 小时前
算法:Fizz Buzz解题思路
c++·算法·leetcode
玛卡巴卡ldf13 小时前
【LeetCode 手撕算法】(细节知识点总结)
java·数据结构·算法·leetcode·力扣
tkevinjd15 小时前
力扣322-零钱兑换
算法·leetcode·动态规划
Frostnova丶16 小时前
(13)LeetCode 53. 最大子数组和
算法·leetcode·职场和发展
什巳16 小时前
JAVA练习277- 找到字符串中所有字母异位
java·开发语言·算法·leetcode
Sw1zzle1 天前
算法入门(四):二叉树 - 递归遍历三件套
算法·leetcode