【力扣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. 个人认为这道题的实际意义不大,主要是吓唬人
相关推荐
老鼠只爱大米2 小时前
LeetCode经典算法面试题 #114:二叉树展开为链表(递归、迭代、Morris等多种实现方案详细解析)
算法·leetcode·二叉树·原地算法·morris遍历·二叉树展开
参.商.2 小时前
【Day25】26.删除有序数组中的重复项 80.删除有序数组中的重复项II
leetcode·golang
执着2593 小时前
力扣hot100 - 144、二叉树的前序遍历
数据结构·算法·leetcode
散峰而望3 小时前
【算法竞赛】树
java·数据结构·c++·算法·leetcode·贪心算法·推荐算法
Anastasiozzzz3 小时前
LeetCode hot100 45 跳跃游戏2
算法·leetcode·游戏
Tisfy3 小时前
LeetCode 3013.将数组分成最小总代价的子数组 II:两个堆维护k-1小 + 滑动窗口
算法·leetcode·题解·优先队列··有序集合·滑动窗口
季明洵4 小时前
反转字符串、反转字符串II、反转字符串中的单词
java·数据结构·算法·leetcode·字符串
后来后来啊5 小时前
2026.2.2 & 2.3学习笔记
数据结构·笔记·学习·算法·leetcode
YuTaoShao6 小时前
【LeetCode 每日一题】3013. 将数组分成最小总代价的子数组 II
算法·leetcode·职场和发展
爱尔兰极光6 小时前
LeetCode 热题 100--字母异位词分组
算法·leetcode·职场和发展