20250207力扣每日一题

知识点
- 方向数组:配合方向index进行使用,可以在有规律的方向移动中进行使用
vector<vector<int>> directions = {{0, 1}, {1, 0}, {0, -1}, {-1, 0}};
// 分别代表方向右、下、左、上
解题思路
- 本题的主要思路为模拟矩阵的生成过程
- 模拟过程的难点在于方向的转换,本题我们将矩阵左上角的方块定义为
(0, 0)
,即row = 0, col = 0
- 接下来我们定义一个方向转换数组,从题中观察可得,初始化的方向为右、下、左、上,所以我们的方向转化数组也模仿此过程。定义如下
vector<vector<int>> directions = {{0, 1}, {1, 0}, {0, -1}, {-1, 0}};
// 分别代表方向右、下、左、上
- 配合
directionIndex
(确定方块的移动方向)进行使用,directionIndex
初始化为0,每次变化为directionIndex = (directionIndex + 1) % 4
- 能够让方向切换的情况主要由以下几种:
- 下一步移动出界
- 下一步移动的方位上元素值非0
- 如此,初始化方块进行移动,直至所有元素都被赋值
实现代码
class Solution {
public:
vector<vector<int>> generateMatrix(int n) {
// 模拟
int maxNum = n * n;
int cur = 1;
// 定义矩阵当前元素的值
vector<vector<int>> matrix(n, vector<int>(n));
// 初始化矩阵,全为0
int row = 0, col = 0;
// 矩阵的左上角定义为(0, 0)
vector<vector<int>> directions = {{0, 1}, {1, 0}, {0, -1}, {-1, 0}};
// 右,下,左,上
int directionIndex = 0;
// 当初始化元素指针“碰壁”后,该变量指定指针顺时针移动的方向
while(cur <= maxNum){
matrix[row][col] = cur;
// 为当前元素赋值
cur ++;
int nextRow = row + directions[directionIndex][0];
int nextCol = col + directions[directionIndex][1];
// 检验下一行列的位置
if(nextRow < 0 || nextRow >= n || nextCol < 0 || nextCol >= n || matrix[nextRow][nextCol]){
// 如果下一行列超出矩阵边框或者“碰壁”,就要转向
directionIndex = (directionIndex + 1) % 4;
}
// 经过检验后的移动方向
row += directions[directionIndex][0];
col += directions[directionIndex][1];
}
// 返回赋值后的矩阵
return matrix;
}
};
Enjoy Reading This Article?
Here are some more articles you might like to read next: