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
        
相关推荐
小欣加油1 分钟前
leetcode3689最大子数组总值I
c++·算法·leetcode·职场和发展·贪心算法
人道领域1 小时前
【LeetCode刷题日记】90.子集Ⅱ--- 归纳题解
java·开发语言·leetcode
小欣加油2 小时前
leetcode121买卖股票的最佳时机
数据结构·c++·算法·leetcode·职场和发展
开源Z3 小时前
LeetCode 238 · 除自身以外数组的乘积:左右两遍扫描,不用除法
算法·leetcode
8Qi83 小时前
LeetCode 5:最长回文子串(Longest Palindromic Substring)—— 题解
算法·leetcode·职场和发展·动态规划
如竟没有火炬14 小时前
最大矩阵——单调栈
数据结构·python·线性代数·算法·leetcode·矩阵
8Qi814 小时前
LeetCode 1143 & 718:最长公共子序列 / 最长重复子数组
算法·leetcode·职场和发展·动态规划
想吃火锅100515 小时前
【leetcode】1.两数之和js版
javascript·算法·leetcode
如何原谅奋力过但无声20 小时前
【灵神高频面试题合集09-13】二叉树、二叉搜索树
数据结构·算法·leetcode
小欣加油21 小时前
leetcode2161 根据给定数字划分数组
数据结构·c++·算法·leetcode·职场和发展