Leetcode54-螺旋矩阵

Leetcode54-螺旋矩阵

在这里插入图片描述

思路:

依次向右向下向左向上遍历。
使用while来控制循环:
while(true)作为无限循环,经常在不知道循环次数的时候使用,并且需要在循环内使用break才会停止。
break条件:left>right or top>botton

代码:

class Solution:
    def spiralOrder(self, matrix: List[List[int]]) -> List[int]:
        left, right = 0, len(matrix[0]) - 1
        top, botton = 0, len(matrix) - 1
        res = []
        while True: #不知道循环次数的时候使用
            for i in range(left, right + 1):
                #向右遍历
                res.append(matrix[top][i])
            top += 1 #下一行
            if top > botton:
                break
            for i in range(top, botton + 1):
                #向下遍历
                res.append(matrix[i][right])
            right -= 1 #左移
            if left > right:
                break
            for i in range(right, left - 1, -1):
                res.append(matrix[botton][i])
            botton -= 1
            if top > botton:
                break
            for i in range(botton, top - 1, -1):
                res.append(matrix[i][left])
            left += 1
            if left > right:
                break
            
        return res
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值