螺旋矩阵的python3题解

本文介绍了一个Python3中的解决方案,用于求解螺旋遍历二维矩阵的问题,通过directions变量控制行和列的移动,遇到非法位置时动态改变方向。
摘要由CSDN通过智能技术生成

螺旋矩阵 通过directions来改变方向,[0,1],[1,0],[0,-1],[-1,0]分别表示右、下、左、上。第一个维度表示行的偏移量,第二个维度表示列的偏移量。遇到非法位置(访问过或者超出边界]就转向.

python3题解:

class Solution:
    def spiralOrder(self, matrix: List[List[int]]) -> List[int]:
        if not matrix or not matrix[0]:
            return list()
        rows,columns = len(matrix),len(matrix[0]) #行数 列数
        total = rows * columns
        row,column = 0,0 #初始位置
        directions = [[0,1],[1,0],[0,-1],[-1,0]]
        direction_index = 0
        visit = [[False] * columns for _ in range(rows)]
        order = [0]*total
        for i in range(total):
            order[i] = matrix[row][column]
            visit[row][column] = True
            nextrow,nextcolumn = row + directions[direction_index][0],column + directions[direction_index][1]
            if not(0 <= nextrow <rows and 0 <= nextcolumn <columns and not visit[nextrow][nextcolumn]):#这个矩阵位置如果非法,就改变方向
              direction_index= (direction_index+1)%4
            row += directions[direction_index][0]
            column += directions[direction_index][1]
        return order

评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值