解题思路笔记
问题理解
我们需要在一个 n x n 的方阵中按照蛇形顺序填充数字。蛇形填充意味着我们需要按照顺时针方向,从方阵的外层开始,逐层向内填充数字。每一层的填充顺序是:
- 从右上角开始,向左填充。
- 从左上角开始,向下填充。
- 从左下角开始,向右填充。
- 从右下角开始,向上填充。
数据结构选择
我们可以使用一个二维列表(Python中的列表嵌套列表)来表示这个方阵。
算法步骤
- 初始化方阵:创建一个
n x n的二维列表,所有元素初始化为0。 - 定义填充方向:我们可以使用一个方向数组来表示填充的方向,例如
[(0, -1), (1, 0), (0, 1), (-1, 0)]分别表示向左、向下、向右、向上。 - 填充数字:从右上角开始,按照定义的方向逐层填充数字。每填充一层,更新当前位置和方向。
- 边界处理:在填充过程中,需要注意边界条件,避免越界。
伪代码框架
def solution(n: int) -> list: # 初始化方阵 matrix = [[0] * n for _ in range(n)]
# 定义方向数组
directions = [(0, -1), (1, 0), (0, 1), (-1, 0)]
# 初始位置和方向
x, y = 0, n - 1
direction_index = 0
# 填充数字
for num in range(1, n * n + 1):
matrix[x][y] = num
# 计算下一个位置
next_x = x + directions[direction_index][0]
next_y = y + directions[direction_index][1]
# 检查是否需要改变方向
if not (0 <= next_x < n and 0 <= next_y < n and matrix[next_x][next_y] == 0):
direction_index = (direction_index + 1) % 4
next_x = x + directions[direction_index][0]
next_y = y + directions[direction_index][1]
# 更新当前位置
x, y = next_x, next_y
return matrix
#### 关键步骤解释
-
初始化方阵:
python
matrix = [[0] * n for
_ in range(n)]
这行代码创建了一个
n x n的二维列表,所有元素初始化为0。 -
定义方向数组:
python
directions = [(0,
-1), (1, 0), (0, 1),
(-1, 0)]
这个方向数组表示从右上角开始,顺时针方向的移动:向左、向下、向右、向上。
-
填充数字:
python
for num in range(1, n
* n + 1):
matrix[x][y] = num
使用一个循环来填充数字,从1到
n * n。 -
计算下一个位置:
python
next_x = x +
directions
[direction_index][0]
next_y = y +
directions
[direction_index][1]
根据当前方向计算下一个位置。
-
检查是否需要改变方向:
python
if not (0 <= next_x <
n and 0 <= next_y < n
and matrix[next_x]
[next_y] == 0):
direction_index =
(direction_index
+ 1) % 4
next_x = x +
directions
[direction_index]
[0]
next_y = y +
directions
[direction_index]
[1]
如果下一个位置越界或已经被填充,则改变方向。
-
更新当前位置:
python
x, y = next_x, next_y
更新当前位置为下一个位置。
总结
通过这些步骤,我们可以实现蛇形填充 n x n 方阵的逻辑。关键在于正确地定义方向数组和处理边界条件。希望这篇笔记能帮助你更好地理解这个问题。如果还有其他问题,请告诉我!