【力扣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. 个人认为这道题的实际意义不大,主要是吓唬人
相关推荐
Sw1zzle2 小时前
算法入门(四):二叉树 - 递归遍历三件套
算法·leetcode
海石3 小时前
子树怎么找?树的3种遍历方式来帮忙!
算法·leetcode
海石3 小时前
难度分 1588:思路 + 技巧 = AC
算法·leetcode
Frostnova丶11 小时前
(12)LeetCode 76. 最小覆盖子串
算法·leetcode·职场和发展
wabs66612 小时前
关于动态规划【力扣583.两个字符串的删除操作的思考】
算法·leetcode·动态规划
_Doubletful13 小时前
妙用位运算:解构汉明距离至100%(提供分析与多解)
c语言·算法·leetcode
凯瑟琳.奥古斯特13 小时前
力扣1013三等分解法与C++实现
开发语言·c++·算法·leetcode·职场和发展
凯瑟琳.奥古斯特14 小时前
力扣1012数位DP解法详解
开发语言·c++·算法·leetcode·职场和发展
海石1 天前
1500分的题目,确实有实力,不过还是我略胜一筹
算法·leetcode
海石1 天前
【记忆化搜索】条条大路通AC,走好适合你的那一条,走到后再考虑走得快
算法·leetcode