【力扣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. 个人认为这道题的实际意义不大,主要是吓唬人
相关推荐
YGGP12 分钟前
【Golang】LeetCode 287. 寻找重复数
开发语言·leetcode·golang
前端小白在前进12 分钟前
力扣刷题:千位分割数
javascript·算法·leetcode
小年糕是糕手18 分钟前
【C/C++刷题集】string类(一)
开发语言·数据结构·c++·算法·leetcode
努力学算法的蒟蒻24 分钟前
day40(12.21)——leetcode面试经典150
算法·leetcode·面试
yuniko-n37 分钟前
【力扣 SQL 50】子查询篇
数据库·sql·leetcode
月明长歌41 分钟前
Java数据结构:PriorityQueue堆与优先级队列:从概念到手写大根堆
java·数据结构·python·leetcode·
月明长歌1 小时前
【码道初阶】LeetCode面试题 17.14 最小 K 个数:两种堆解法的“同题不同命”
算法·leetcode·职场和发展
LYFlied1 小时前
【每日算法】LeetCode238. 除自身以外数组的乘积
数据结构·算法·leetcode·面试·职场和发展
元亓亓亓1 小时前
LeetCode热题100--118. 杨辉三角--简单
算法·leetcode·职场和发展
杜子不疼.2 小时前
【LeetCode 35 & 69_二分查找】搜索插入位置 & x的平方根
算法·leetcode·职场和发展