LeetCode刷题|54螺旋矩阵

今天的每日一题是一道关于遍历矩阵的题目。先看一下题目长啥样。
在这里插入图片描述
LeetCode地址:螺旋矩阵

解法一

第一种方法很自然的就可以想到,每次遍历到行末或者列末就转向,但是如何设计使得到达末尾就转向比较麻烦。我们可以使用一个转向数组,里面存放-1,0,1三种数,-1表示减一,0表示不动,1表示加一,前进一步。那么一个数组[0,1],第一位是行,第二位是列的话,就可以用这个数组表示行不动,列每一次加一,也就是往右前进。以此类推[1,0]就表示往下前进,[-1,0]表示往左前进,[0,-1]表示往上前进。这样我们每次碰到边界之后就在这四个方向中转化,以此达到螺旋遍历的目的。
另外还需要维护一个与矩阵同样大的矩阵,用来记录对应元素是否已经被遍历过。如果前面的元素被遍历过了,说明到了边界,就转向。

class Solution:
    def spiralOrder(self, matrix: List[List[int]]) -> List[int]:
        r,c = len(matrix),len(matrix[0])
        n = r*c
        order = [0] * (n)
        visited = [[False] * c for _ in range(r)]

        direction = [[0,1],[1,0],[0,-1],[-1,0]]
        directionIndex = 0
        row,col = 0,0
        for i in range(n):
            order[i] = matrix[row][col]
            visited[row][col] = True
            newrow,newcol = row + direction[directionIndex][0], col + direction[directionIndex][1]
            if not 0<= newrow < r or not 0 <= newcol < c or visited[newrow][newcol] == True:
                directionIndex = (directionIndex+1)%4
            row,col = row + direction[directionIndex][0], col + direction[directionIndex][1]
        return order

代码中的direction数组就是用来控制转向的数组了,directionIndex用来表示往前后左右哪个方向来转,每当遇到边界条件,directionIndex就加一,表示转向一次。

方法二

方法二是将矩阵看成是一层一层的,从外层开始遍历,逐渐遍历到中间。使用left, right, top, bottom来表示每一层的边界。遍历完一次之后,left和top加一,right和bottom减一,这样就开始了下一层的遍历。当left和right相遇,或者top和bottom相遇就遍历结束。

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])
        order = list()
        left, right, top, bottom = 0, columns - 1, 0, rows - 1
        while left <= right and top <= bottom:
            for column in range(left, right + 1):
                order.append(matrix[top][column])
            for row in range(top + 1, bottom + 1):
                order.append(matrix[row][right])
            if left < right and top < bottom:
                for column in range(right - 1, left, -1):
                    order.append(matrix[bottom][column])
                for row in range(bottom, top, -1):
                    order.append(matrix[row][left])
            left, right, top, bottom = left + 1, right - 1, top + 1, bottom - 1
        return order
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值