腾讯16-螺旋矩阵

腾讯16-螺旋矩阵leetcode54

给定一个包含 m x n 个元素的矩阵(m 行, n 列),请按照顺时针螺旋顺序,返回矩阵中的所有元素。

示例 1:

输入:
[
[ 1, 2, 3 ],
[ 4, 5, 6 ],
[ 7, 8, 9 ]
]
输出: [1,2,3,6,9,8,7,4,5]
示例 2:

输入:
[
[1, 2, 3, 4],
[5, 6, 7, 8],
[9,10,11,12]
]
输出: [1,2,3,4,8,12,11,10,9,5,6,7]

思路就是暴力,
但是写出逻辑清晰的暴力,还是很不容易,关键是用python的range在边界容易出错,最好不用for的range,都用while

def spiralOrder(self, matrix: List[List[int]]) -> List[int]:
    if len(matrix)==0 or len(matrix[0])==0:
        return []
    else:
        #虽然是暴力,但是有逻辑的写出暴力也不容易
        row_begin,col_begin=0,0
        row_end,col_end=len(matrix)-1,len(matrix[0])-1
        res=[]
        while(row_begin<=row_end and  col_begin<=col_end):
            for i in range(col_begin,col_end+1):#[col_begin,col_end】从col_begin取到col_end
                res.append(matrix[row_begin][i])
            row_begin+=1
            for i in range(row_begin,row_end+1):
                res.append(matrix[i][col_end])
            col_end-=1
            if(row_begin<=row_end ):
                for i in range(col_end,col_begin-1,-1):#[col_begin,col_end】从col_begin取到col_end
                    res.append(matrix[row_end][i])
            row_end-=1
            if(col_begin<=col_end ):
                for i in range(row_end,row_begin-1,-1):#[col_begin,col_end】从col_begin取到col_end
                    res.append(matrix[i][col_begin])
            col_begin+=1
        return res
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值