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
        
相关推荐
倦王4 小时前
力扣日刷47-补
python·算法·leetcode
无限进步_5 小时前
【C++】巧用静态变量与构造函数:一种非常规的求和实现
开发语言·c++·git·算法·leetcode·github·visual studio
凌波粒6 小时前
LeetCode--344.反转字符串(字符串/双指针法)
算法·leetcode·职场和发展
啊哦呃咦唔鱼6 小时前
LeetCode hot100-543 二叉树的直径
算法·leetcode·职场和发展
样例过了就是过了7 小时前
LeetCode热题100 爬楼梯
c++·算法·leetcode·动态规划
ThisIsMirror7 小时前
leetcode 452 Arrays.sort()排序整数溢出、Integer.compare(a[1], b[1])成功的问题
算法·leetcode
x_xbx9 小时前
LeetCode:438. 找到字符串中所有字母异位词
算法·leetcode·职场和发展
派大星~课堂9 小时前
【力扣-94.二叉树的中序遍历】Python笔记
笔记·python·leetcode
AI成长日志10 小时前
【笔面试算法学习专栏】堆与优先队列实战:力扣hot100之215.数组中的第K个最大元素、347.前K个高频元素
学习·算法·leetcode
6Hzlia10 小时前
【Hot 100 刷题计划】 LeetCode 45. 跳跃游戏 II | C++ 贪心算法最优解题解
c++·leetcode·游戏