【力扣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. 个人认为这道题的实际意义不大,主要是吓唬人
相关推荐
alphaTao7 小时前
LeetCode 每日一题 2026/2/2-2026/2/8
算法·leetcode
甄心爱学习7 小时前
【leetcode】判断平衡二叉树
python·算法·leetcode
不知名XL7 小时前
day50 单调栈
数据结构·算法·leetcode
@––––––8 小时前
力扣hot100—系列2-多维动态规划
算法·leetcode·动态规划
YuTaoShao9 小时前
【LeetCode 每日一题】1653. 使字符串平衡的最少删除次数——(解法三)DP 空间优化
算法·leetcode·职场和发展
TracyCoder12310 小时前
LeetCode Hot100(26/100)——24. 两两交换链表中的节点
leetcode·链表
望舒51311 小时前
代码随想录day25,回溯算法part4
java·数据结构·算法·leetcode
铉铉这波能秀12 小时前
LeetCode Hot100数据结构背景知识之集合(Set)Python2026新版
数据结构·python·算法·leetcode·哈希算法
参.商.12 小时前
【Day 27】121.买卖股票的最佳时机 122.买卖股票的最佳时机II
leetcode·golang
铉铉这波能秀13 小时前
LeetCode Hot100数据结构背景知识之元组(Tuple)Python2026新版
数据结构·python·算法·leetcode·元组·tuple