【力扣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. 个人认为这道题的实际意义不大,主要是吓唬人
相关推荐
旖旎夜光14 分钟前
LCR 170:交易逆序对的总数(归并排序) —— 题解
c++·学习·算法·leetcode·排序算法
圣保罗的大教堂14 小时前
leetcode 3619. 总价值可以被 K 整除的岛屿数目 中等
leetcode
文丑颜不良啊20 小时前
LeetCode1141~1160题目解析
java·leetcode
木井巳20 小时前
【动态规划: 路径问题】下降路径最小和
java·算法·leetcode·动态规划·推荐算法
ynchyong21 小时前
培养程序化思维
leetcode·程序化思维·刷题经验
YLCHUP1 天前
【模拟&STL】题解:AT_abc203_e [ABC203E] White Pawn_基础算法_数据结构_STL模板库_AtcoderABC_C++算法竞赛
数据结构·c++·算法·leetcode·动态规划·哈希算法·近邻算法
(●—●)橘子……1 天前
力扣 第525场周赛 练习理解
数据结构·python·学习·算法·leetcode
wenyq71 天前
LeetCode 152. Maximum Product Subarray
java·算法·leetcode
文丑颜不良啊1 天前
LeetCode1181~1200题目解析
java·leetcode
海绵宝宝转agent1 天前
Leetcode100+面经
java·笔记·学习·算法·leetcode·深度优先