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
相关推荐
罗湖老棍子1 分钟前
【例9.10】机器分配(信息学奥赛一本通- P1266) 机器分配(洛谷P2066)
算法·动态规划·多重背包
roman_日积跬步-终至千里16 分钟前
【计算机视觉(2)】图像几何变换基础篇:从平移旋转到投影变换
人工智能·算法·计算机视觉
R-G-B18 分钟前
OpenCV Python——窗口滑动条,TrackBar控件,createTrackbar(),getTrackbarPos(),
python·callback·trackbar·窗口滑动条·trackbar控件·createtrackbar·gettrackbarpos
0 0 021 分钟前
CCF-CSP 37-3 模板展开(templating)【C++】
c++·算法
im_AMBER22 分钟前
Leetcode 71 买卖股票的最佳时机 | 增量元素之间的最大差值
笔记·学习·算法·leetcode
ranchor66624 分钟前
pandas 模拟题
开发语言·python·pandas
bulingg25 分钟前
聚类方法(kmeans,DBSCAN,层次聚类,GMM,EM算法)
算法·kmeans·聚类
lally.27 分钟前
Kaggle Binary Classification with a Bank Dataset逻辑回归实现(准确率0.94539)
人工智能·算法·机器学习·逻辑回归
埃伊蟹黄面27 分钟前
二分查找算法
c++·算法·leetcode
野蛮人6号31 分钟前
力扣热题100道之78子集
算法·leetcode·职场和发展