Python编程之旅:Leetcode每日一题-螺旋矩阵2
模拟定义四个变量left、right、top、bottom分别表示当前矩阵的左、右、上、下边界。bottom)用于向矩阵matrix的[left:
今天我们来讲解一道比较有趣的Leetcode每日一题——螺旋矩阵2。这道题目是关于矩阵操作的,需要我们按照顺时针方向依次填入1~n^2这些自然数,最终得到一个n*n的矩阵。对于初学者来说,这道题可能会稍微有些困难,但是只要掌握了一定的技巧和方法,就能够轻松地解决它。
问题描述
给定一个正整数n,生成一个包含1~n^2所有元素,并按顺时针顺序填充的n×n矩阵。
示例:
输入: 3
输出:
[
[ 1, 2, 3 ],
[ 8, 9, 4 ],
[ 7, 6, 5 ]
]
解法思路
在开始编写代码之前,我们首先需要理清楚本题的解法思路。对于这种涉及到二维数组操作、遍历方式等问题,在解决之前最好先画图模拟一下整个过程。下面给出本题常用的两种方法:
方法一:模拟
定义四个变量left、right、top、bottom分别表示当前矩阵的左、右、上、下边界。从左到右,从上到下,从右到左,从下到上遍历每个格子,并按顺序填入1~n^2这些自然数。
具体步骤如下:
1. 初始化left=0,right=n-1,top=0,bottom=n-1。
2. 循环直至left>right或top>bottom:
① 从左往右:将第top行中所有未填元素依次填入
② 从上往下:将第right列中所有未填元素依次填入
③ 从右往左:将第bottom行中所有未填元素依次填入
④ 从下往上:将第left列中所有未填元素依次填入
3. 返回生成的矩阵。
方法二:递归
在方法一的基础上,我们可以使用递归来实现。首先定义一个函数fillMatrix(matrix, left, right, top, bottom)用于向矩阵matrix的[left:right+1][top:bottom+1]区域内按顺时针顺序依次填充数字n^2…n^2-(right-left+bottom-top)*4+4,并返回最终生成的矩阵。然后,在主函数中调用fillMatrix(matrix,0,n-1,0,n-1)即可得到解答。
代码实现
接着,我们就可以开始编写代码了。下面给出方法一和方法二的具体实现:
方法一:
“`python
class Solution:
def generateMatrix(self, n: int) -> List[List[int]]:
matrix = [[0] * n for _ in range(n)]
left, right, top, bottom = 0, n – 1, 0, n – 1
num = 1
while left <= right and top <= bottom:
for i in range(left,right+1):
matrix[top][i] = num
num += 1
for j in range(top+1,bottom+1):
matrix[j][right] = num
num += 1
![Python编程之旅:Leetcode每日一题-螺旋矩阵2缩略图 Python编程之旅:Leetcode每日一题-螺旋矩阵2](https://www.72715.net/wp-content/uploads/2023/05/67cfddddc9c22a08d46c5f82a0df4306.png)
if left < right and top < bottom:
for i in range(right-1,left,-1):
matrix[bottom][i] = num
num += 1
for j in range(bottom,top,-1):
matrix[j][left] = num
left,right,top,bottom=left+1,right-1,top+1,bottom-11
return matrix
“`
方法二:
def fillMatrix(matrix,left,right,top,bottom,num):
if left > right or top > bottom:
return
if left == right and top == bottom:
matrix[top][left] =num
return
for i in range(left,right): #从左到右遍历上侧元素(不含最后一个)
matrix[top][i]=num
num+=10
本文主要讲解了Leetcode每日一题-螺旋矩阵2的解题思路和代码实现。通过对这道题目的分析,我们不仅掌握了二维数组操作、遍历方式等相关知识,还深入理解了方法一和方法二的编写原理。希望大家在学习过程中能够多加练习,并逐步提高自己的编程水平。
最后附上本文所涉及到的所有代码,请大家自行参考:
num += 10
left,right,top,bottom=left+10,right-10,top+10,bottom-110
def generateMatrix(self,n:int)->List[List[int]]:
matrix=[[0]*n for _ in range(n)]
fillMatrix(matrix,0,n-1,0,n-1,1)
return matrix
def fillMatrix(matrix,left,right,top,bottom,num):
if left > right or top > bottom:
return
if left == right and top == bottom:
matrix[top][left] =num
return
for i in range(left,right): #从左到右遍历上侧元素(不含最后一个)
matrix[top][i]=num
num+=10
for i in range(top,bottom): #从上到下遍历右侧元素(不含最后一个)
matrix[i][right]=num