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
        
相关推荐
zander2583 分钟前
LeetCode 198. 打家劫舍
算法·leetcode·深度优先
吃着火锅x唱着歌10 分钟前
LeetCode 648.单词替换
算法·leetcode·职场和发展
Elsa️74635 分钟前
leetcode 14.最长公共前缀
算法·leetcode·职场和发展
203号居民14 小时前
LeetCode hot 100 —41. 缺失的第一个正数
数据结构·算法·leetcode
evans在进步17 小时前
LeetCode 322:零钱兑换——Java 动态规划详解
java·leetcode·动态规划
Tisfy19 小时前
LeetCode 3471.找出最大的几近缺失整数:三种情况判断
算法·leetcode·题解·分类讨论
青 春 记 忆1 天前
LeetCode 121. 买卖股票的最佳时机|Python 解法详解
python·算法·leetcode
rannn_1111 天前
【力扣hot100】二叉树专题
算法·leetcode·职场和发展
Navigator_Z1 天前
LeetCode //C - 1203. Sort Items by Groups Respecting Dependencies
c语言·算法·leetcode
Scabbards_2 天前
面试Leetcode - Heap 堆
java·leetcode·面试