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 天前
Effective STL 条款 07:指针容器销毁前先删除
开发语言·c++·vscode·leetcode·rpc·visual studio
CoderYanger1 天前
A.每日一题:2243. 计算字符串的数字和
java·开发语言·程序人生·leetcode·面试·蓝桥杯·学习方法
Navigator_Z1 天前
LeetCode //C - 1323. Maximum 69 Number
c语言·算法·leetcode
Pniubi3 天前
力扣2 . 两数相加
算法·leetcode·职场和发展
文丑颜不良啊3 天前
LeetCode3401~3420题目解析
java·leetcode
文丑颜不良啊3 天前
LeetCode3421~3440题目解析
java·leetcode
LK_074 天前
【力扣】142. 环形链表 II |Python
python·leetcode·链表
Pniubi4 天前
力扣21合并两个有序链表
算法·leetcode·职场和发展
文丑颜不良啊4 天前
LeetCode3341~3360题目解析
java·leetcode
Rain的Java大神之路4 天前
把数组本身变成哈希表:原地哈希搞定 LeetCode 41「缺失的第一个正数」
java·后端·leetcode