【力扣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. 个人认为这道题的实际意义不大,主要是吓唬人
相关推荐
sheeta19982 小时前
LeetCode 每日一题笔记 日期:2025.11.24 题目:1018. 可被5整除的二进制前缀
笔记·算法·leetcode
橘颂TA9 小时前
【剑斩OFFER】算法的暴力美学——两整数之和
算法·leetcode·职场和发展
Dream it possible!10 小时前
LeetCode 面试经典 150_二叉搜索树_二叉搜索树的最小绝对差(85_530_C++_简单)
c++·leetcode·面试
xxxxxxllllllshi10 小时前
【LeetCode Hot100----14-贪心算法(01-05),包含多种方法,详细思路与代码,让你一篇文章看懂所有!】
java·数据结构·算法·leetcode·贪心算法
-森屿安年-13 小时前
LeetCode 283. 移动零
开发语言·c++·算法·leetcode
元亓亓亓16 小时前
LeetCode热题100--79. 单词搜索
算法·leetcode·职场和发展
2501_9411437316 小时前
缓存中间件Redis与Memcached在高并发互联网系统优化与实践经验分享
leetcode
Elias不吃糖18 小时前
LeetCode每日一练(209, 167)
数据结构·c++·算法·leetcode
野蛮人6号20 小时前
力扣热题100道前62道,内容和力扣官方稍有不同,记录了本人的一些独特的解法
数据结构·算法·leetcode
CoderYanger1 天前
优选算法-栈:69.验证栈序列
java·开发语言·算法·leetcode·职场和发展·1024程序员节