【力扣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. 个人认为这道题的实际意义不大,主要是吓唬人
相关推荐
洛水水4 小时前
【力扣100题】53.最长回文子串
算法·leetcode·职场和发展
过期动态5 小时前
【LeetCode 热题 100】盛最多水的容器
java·数据结构·spring boot·算法·leetcode·spring cloud·职场和发展
凌波粒5 小时前
LeetCode--700.二叉搜索树中的搜索(二叉树)
算法·leetcode·职场和发展
洛水水6 小时前
【力扣100题】58.轮转数组
算法·leetcode
风筝在晴天搁浅6 小时前
阿里 LeetCode 876.链表的中间节点
算法·leetcode·链表
玖釉-6 小时前
二叉树展开为链表:从先序遍历到原地指针重排
c++·windows·算法·leetcode·链表
洛水水7 小时前
【力扣100题】52.最小路径和
算法·leetcode
圣保罗的大教堂7 小时前
leetcode 3043. 最长公共前缀的长度 中等
leetcode
菜菜的顾清寒10 小时前
力扣HOT100(34)图论-岛屿数量
算法·leetcode·图论
圣保罗的大教堂10 小时前
leetcode 2657. 找到两个数组的前缀公共数组 中等
leetcode