【力扣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. 个人认为这道题的实际意义不大,主要是吓唬人
相关推荐
Adios7943 小时前
设置交集大小至少为2
数据结构·算法·leetcode
程序猿乐锅11 小时前
【数据结构与算法 | 第六篇】力扣1109,1094差分数组
java·算法·leetcode
hold?fish:palm14 小时前
9 找到字符串中所有字母异位词
c++·算法·leetcode
Sw1zzle15 小时前
算法入门(六):贪心算法 - 基础入门(Leetcode 121/455/860/376/738)
算法·leetcode·贪心算法
青山木15 小时前
Hot 100 --- 岛屿数量
java·数据结构·算法·leetcode·深度优先·广度优先
啦啦啦啦啦zzzz16 小时前
算法:回溯算法
c++·算法·leetcode
小肝一下18 小时前
3. 单链表
c语言·数据结构·c++·算法·leetcode·链表·dijkstra
tachibana218 小时前
hot100 前 K 个高频元素(347)
java·数据结构·算法·leetcode
To_OC1 天前
LC 131 分割回文串:刚学回溯时,我连怎么切字符串都想不明白
javascript·算法·leetcode
旖-旎1 天前
LeetCode 518:零钱兑换||(完全背包)—— 题解
c++·算法·leetcode·动态规划·背包问题