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
相关推荐
文言一心33 分钟前
LINUX离线升级 Python 至 3.11.9 操作手册
linux·运维·python
北邮刘老师41 分钟前
智能体治理:人工智能时代信息化系统的全新挑战与课题
大数据·人工智能·算法·机器学习·智能体互联网
诗词在线1 小时前
中国古代诗词名句按主题分类有哪些?(爱国 / 思乡 / 送别)
人工智能·python·分类·数据挖掘
高锰酸钾_1 小时前
机器学习-L1正则化和L2正则化解决过拟合问题
人工智能·python·机器学习
AlenTech1 小时前
155. 最小栈 - 力扣(LeetCode)
算法·leetcode·职场和发展
mit6.8241 小时前
正反两次扫描|单调性cut
算法
天天睡大觉1 小时前
Python学习11
网络·python·学习
智航GIS1 小时前
11.11 Pandas性能革命:向量化操作与内存优化实战指南
python·pandas
Yzzz-F2 小时前
牛客小白月赛127 E
算法