【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
相关文章
- Java实现 LeetCode 762 二进制表示中质数个计算置位(位运算+JDK的方法)
- Java实现 LeetCode 566 重塑矩阵(遍历矩阵)
- Java实现 LeetCode 378 有序矩阵中第K小的元素
- Java实现 LeetCode 329 矩阵中的最长递增路径
- Java实现 LeetCode 242 有效的字母异位词
- Java实现 LeetCode 8 字符串转换整数(atoi)
- LeetCode-417. 太平洋大西洋水流问题【DFS,BFS,数组,矩阵】
- LeetCode-385. 迷你语法分析器【深度优先搜索,栈】
- Leetcode 73. 矩阵置零
- Leetcode 1352. 最后 K 个数的乘积(不知为啥会超时)
- Leetcode 1337. 矩阵中战斗力最弱的 K 行
- [LeetCode] 240. 搜索二维矩阵 II ☆☆☆(二分查找类似)
- leetcode 1. Two Sum
- leetcode 746. Min Cost Climbing Stairs
- 【Leetcode刷题Python】剑指 Offer 33. 二叉搜索树的后序遍历序列
- 【LeetCode】剑指 Offer II 109. 开密码锁