【力扣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. 个人认为这道题的实际意义不大,主要是吓唬人
相关推荐
迪小莫学AI8 分钟前
【力扣每日一题】划分数组并满足最大差限制
算法·leetcode·职场和发展
_DF1 小时前
【Fifty Project - D37】
leetcode
CodeWithMe1 小时前
【Leetcode】每日一题 —— No.2966
算法·leetcode
圣保罗的大教堂15 小时前
leetcode 2566. 替换一个数字后的最大差值 简单
leetcode
剪一朵云爱着15 小时前
力扣面试题 17.05. 字母与数字
算法·leetcode
wen__xvn17 小时前
九日集训第三天
数据结构·算法·leetcode
dying_man17 小时前
LeetCode--33.搜索旋转排序数组
算法·leetcode
东方芷兰17 小时前
Leetcode 刷题记录 17 —— 堆
java·c++·b树·算法·leetcode·职场和发展
wen__xvn19 小时前
九日集训第六天
数据结构·算法·leetcode