【力扣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. 个人认为这道题的实际意义不大,主要是吓唬人
相关推荐
203号居民7 小时前
LeetCode hot 100 — 141. 环形链表2
算法·leetcode·链表
玖玥拾8 小时前
LeetCode 202 快乐数
算法·leetcode
Tim_109 小时前
【LeetCode】29、两数相除
算法·leetcode·职场和发展
土司大王16 小时前
LeetCode hot100——缺失的第一个正数
数据结构·算法·leetcode
Cccp.12316 小时前
【leetcode】(二)认识O(NlogN)的排序
算法·leetcode
鹿角片ljp17 小时前
LeetCode 56:合并区间复盘|从排序思维到 List<int[]> 的简洁写法
算法·leetcode·list
玖玥拾18 小时前
LeetCode 205 同构字符串
算法·leetcode
_不会dp不改名_21 小时前
leetcode3875_构造奇偶一致的数组 I
leetcode
圣保罗的大教堂1 天前
leetcode 1406. 石子游戏 III 困难
leetcode
带多刺的玫瑰2 天前
Leecode#15刷题之三数之和
算法·leetcode·职场和发展