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
相关推荐
yenggd4 分钟前
华为批量下发配置命令使用telnetlib模块
网络·python·华为
不惑_18 分钟前
通俗理解感知机(Perceptron)
人工智能·python
Everybody_up21 分钟前
pycharm中编译环境配置
ide·python·pycharm
零小陈上(shouhou6668889)25 分钟前
YOLOv8+PyQt5输电线路缺陷检测(目前最全面的类别检测,可以从图像、视频和摄像头三种路径检测)
python·qt·yolo
luoluoal25 分钟前
基于python的爬虫的贵州菜价可视化系统(源码+文档)
python·mysql·django·毕业设计·源码
2501_9216494930 分钟前
股票 API 对接,接入美国纳斯达克交易所(Nasdaq)实现缠论回测
开发语言·后端·python·websocket·金融
De-Alf36 分钟前
Megatron-LM学习笔记(6)Megatron Model Attention注意力与MLA
笔记·学习·算法·ai
2401_8414956444 分钟前
【LeetCode刷题】打家劫舍
数据结构·python·算法·leetcode·动态规划·数组·传统dp数组
李昊哲小课44 分钟前
简化版天气爬虫教程
爬虫·python
3824278271 小时前
python:Ajax爬取电影详情实战
开发语言·python·ajax