LeetCode54题:螺旋矩阵(python3)

路径的长度即为矩阵中的元素数量,当路径的长度达到矩阵中的元素数量时即为完整路径,将该路径返回。

循环打印: "从左向右、从上向下、从右向左、从下向上" 四个方向循环打印。

python 复制代码
class Solution:
    def spiralOrder(self, matrix: List[List[int]]) -> List[int]:
        if not matrix or not matrix[0]:
            return []
        r,c = len(matrix),len(matrix[0])
        res=[]
        left,right,top,bottom = 0,c-1,0,r-1
        while left<=right and top<=bottom:
            for i in range(left,right+1):
                res.append(matrix[top][i])
            for j in range(top+1,bottom+1):
                res.append(matrix[j][right])
            if left<right and top<bottom:
                for i in range(right-1,left,-1):
                    res.append(matrix[bottom][i])
                for j in range(bottom,top,-1):
                    res.append(matrix[j][left])
            left,right,top,bottom=left+1,right-1,top+1,bottom-1
        return res
相关推荐
熊猫钓鱼>_>23 分钟前
面试出现 606 次的第 K 大,被拆成三个问题问
算法·面试·职场和发展·校招·面经·oj·ai生成
小猴子爱上树23 分钟前
跨马翻译:批量图片翻译+视频字幕+智能抠图,跨境电商翻译工具
python·音视频
棉猴36 分钟前
玩游戏学Python2-IDLE与pgzero入门
开发语言·python·游戏·玩游戏·pgzero·pgzrun
xuxigifxfh39 分钟前
牛客:BISHI2 【模板】栈的操作
java·开发语言·windows·算法
TechEdu20260643 分钟前
[人工智能]Python12: SciPy 实战指南
人工智能·python·scipy
aqiu1111111 小时前
【C++算法打怪专栏】LeetCode 402. 移掉 K 位数字(单调栈 + 贪心)
c++·算法·leetcode
jack186891 小时前
Github Copilot 高效开发实战场景指南
python
AIFQuant1 小时前
Python A股实时行情API接入:沪深股票数据与WebSocket推送实战
开发语言·python·websocket·金融·a股行情
小小龙学IT1 小时前
Python Matplotlib 数据可视化库深度解析
python·信息可视化·matplotlib
糖果豆豆1 小时前
对象是字段,还是关系?集合论和范畴论吵了三十年,答案是两个都对
算法·架构