【力扣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. 个人认为这道题的实际意义不大,主要是吓唬人
相关推荐
Maybyy31 分钟前
力扣61.旋转链表
算法·leetcode·链表
chao_7893 小时前
二分查找篇——搜索旋转排序数组【LeetCode】一次二分查找
数据结构·python·算法·leetcode·二分查找
是白可可呀7 小时前
LeetCode 169. 多数元素
leetcode
YuTaoShao8 小时前
【LeetCode 热题 100】148. 排序链表——(解法二)分治
java·算法·leetcode·链表
蒟蒻小袁10 小时前
力扣面试150题--全排列
算法·leetcode·面试
緈福的街口11 小时前
【leetcode】2236. 判断根节点是否等于子节点之和
算法·leetcode·职场和发展
祁思妙想11 小时前
【LeetCode100】--- 1.两数之和【复习回滚】
数据结构·算法·leetcode
薰衣草233311 小时前
一天两道力扣(2)
算法·leetcode
chao_78911 小时前
二分查找篇——寻找旋转排序数组中的最小值【LeetCode】
python·线性代数·算法·leetcode·矩阵
zstar-_12 小时前
【算法笔记】6.LeetCode-Hot100-链表专项
笔记·算法·leetcode