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 小时前
Leetcode—3. 无重复字符的最长子串【中等】
经验分享·后端·算法·leetcode·面试·golang·string
历程里程碑4 小时前
哈希2:字母异位符分组
算法·leetcode·职场和发展
Stardep5 小时前
算法入门20——二分查找算法——搜索插入位置
数据结构·算法·leetcode
老鼠只爱大米5 小时前
LeetCode经典算法面试题 #141:环形链表(快慢指针、标记节点等多种方法详细解析)
算法·leetcode·链表·快慢指针·floyd算法·环形链表
踩坑记录5 小时前
leetcode hot100 48.旋转图像 矩阵转置
leetcode
鹿角片ljp6 小时前
力扣112. 路径总和:递归DFS vs 迭代BFS
leetcode·深度优先·宽度优先
im_AMBER6 小时前
Leetcode 104 两两交换链表中的节点
笔记·学习·算法·leetcode
程序员-King.6 小时前
day159—动态规划—打家劫舍(LeetCode-198)
c++·算法·leetcode·深度优先·回溯·递归
浅念-6 小时前
C语言——单链表
c语言·开发语言·数据结构·经验分享·笔记·算法·leetcode