zl程序教程

您现在的位置是:首页 >  其他

当前栏目

【LeetCode】剑指 Offer 29. 顺时针打印矩阵

LeetCode 矩阵 打印 Offer 29
2023-09-14 09:13:24 时间

题目

思想

这道题有太多的方法可以实现。递归,for循环等等。下面就用while循环来解决这道题。
抽象一下这道题,发现其实就是将这个矩阵往四个方向的遍历,按照的顺序是 右 =>下 => 左 => 上 => 右 => … 需要分一下循环边界即可。

代码

class Solution:
    def spiralOrder(self, matrix: List[List[int]]) -> List[int]:
        res = [] # 最后存储的值
        if len(matrix) == 0:
            return res
        vis = [[1] * len(matrix[0]) for i in range(len(matrix))]       

        self.dfs(matrix,vis,len(matrix),len(matrix[0]),res)
        return res

    # n 行 m列
    def dfs(self,matrix,vis,n,m,res):
        total = len(matrix) * len(matrix[0]) # 矩阵总数        
        cnt = 0
        x,y = 0,0 # 初始值
        while(cnt < total):
            while(y<m and vis[x][y]):# 右                
                res.append(matrix[x][y])
                vis[x][y] = 0
                y+=1
                cnt += 1
                
            x+=1 # 往下走
            y-=1
            while(x<n and vis[x][y]):                
                res.append(matrix[x][y])
                vis[x][y] = 0
                x+=1
                cnt += 1

            y-=1
            x-=1
            while(y>=0 and vis[x][y]): # 左            
                res.append(matrix[x][y])
                vis[x][y] = 0
                y -= 1
                cnt+=1
            
            x-=1
            y+=1
            while(x>=0 and vis[x][y] ): # 上                
                res.append(matrix[x][y])
                vis[x][y] = 0
                x -= 1
                cnt+=1
            x+=1
            y+=1