【力扣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. 个人认为这道题的实际意义不大,主要是吓唬人
相关推荐
蛋蛋的就会顺顺的8 小时前
hot100 p0——栈,贪心算法,动态规划
java·前端·javascript·算法·leetcode·力扣
Navigator_Z10 小时前
LeetCode //C - 1291. Sequential Digits
c语言·算法·leetcode
0+11115 小时前
算法 --栈
算法·leetcode
圣保罗的大教堂15 小时前
leetcode 3723. 数位平方和的最大值 中等
leetcode
浅念-17 小时前
动态规划:线性DP——多状态DP与子数组专题笔记
c++·笔记·算法·leetcode·职场和发展·动态规划·力扣
学电子她就能回来吗18 小时前
LeetCode Hot 100|滑动窗口专题零基础学习笔记
笔记·学习·leetcode
拾饵94219 小时前
面试回答整理(Q1–Q3)
leetcode
虚无的纽扣19 小时前
【力扣刷题】第四天:三数之和、四数之和
算法·leetcode·职场和发展
_不会dp不改名_20 小时前
leetcode_3273 数位平方和的最大值
算法·leetcode·职场和发展
局部有解20 小时前
Leetcode - 42 接雨水(一维)
数据结构·c++·算法·leetcode