【力扣100】54.螺旋矩阵

添加链接描述

python 复制代码
class Solution:
    def spiralOrder(self, matrix: List[List[int]]) -> List[int]:
        if not matrix or not matrix[0]:
            return list()
        
        rows, columns = len(matrix), len(matrix[0])
        order = list()
        left, right, top, bottom = 0, columns - 1, 0, rows - 1
        while left <= right and top <= bottom:
            for column in range(left, right + 1):
                order.append(matrix[top][column])
            for row in range(top + 1, bottom + 1):
                order.append(matrix[row][right])
            if left < right and top < bottom:
                for column in range(right - 1, left, -1):
                    order.append(matrix[bottom][column])
                for row in range(bottom, top, -1):
                    order.append(matrix[row][left])
            left, right, top, bottom = left + 1, right - 1, top + 1, bottom - 1
        return order

思路:

  1. 按层进行遍历
  2. 然后就是判断每个边界值的条件
  3. 向左和下走是被允许的,向右或向上走是不被允许的需要条件判断
  4. 个人认为这道题的实际意义不大,主要是吓唬人
相关推荐
小白程序员成长日记6 小时前
2025.11.24 力扣每日一题
算法·leetcode·职场和发展
有一个好名字6 小时前
LeetCode跳跃游戏:思路与题解全解析
算法·leetcode·游戏
2501_941870568 小时前
Python在高并发微服务数据同步与分布式事务处理中的实践与优化
leetcode
2501_9411477110 小时前
高并发微服务架构Spring Cloud与Dubbo在互联网优化实践经验分享
leetcode
Swift社区12 小时前
LeetCode 432 - 全 O(1) 的数据结构
数据结构·算法·leetcode
资深web全栈开发13 小时前
LeetCode 1015. 可被 K 整除的最小整数 - 数学推导与鸽巢原理
算法·leetcode·职场和发展
leoufung13 小时前
链表题目讲解 —— 删除链表的倒数第 n 个节点(LeetCode 19)
数据结构·leetcode·链表
CoderYanger13 小时前
优选算法-队列+宽搜(BFS):72.二叉树的最大宽度
java·开发语言·算法·leetcode·职场和发展·宽度优先·1024程序员节
czlczl2002092521 小时前
算法:组合问题
算法·leetcode·职场和发展