396 字
2 分钟
59. 螺旋矩阵 II

59. 螺旋矩阵 II#

给你一个正整数 n ,生成一个包含 1 到 n2 所有元素,且元素按顺时针顺序螺旋排列的 n x n 正方形矩阵 matrix 。

示例 1:
输入:n = 3
输出:[[1,2,3],[8,9,4],[7,6,5]]
示例 2:
输入:n = 1
输出:[[1]]

思路#

  1. 定义一个循环,一圈一圈地遍历,直到遍历到最中间的圈。
  2. 圈数定义为n / 2,当n为奇数时,会有一个单独的元素在中间不被遍历,因此要在最后手动补充。
  3. 每次重置坐标,从左上角开始遍历。在单次圈遍历的过程中,分为4个部分进行遍历。
    1. 假设单圈边长为4,那么在每个边上,遍历[0~2]3个元素
    2. 注意:随着向内前进,要考虑实际的坐标范围。如,第i圈的第一次遍历范围为row = i, col = [i, n - i - 2]

代码#

class Solution {
public:
vector<vector<int>> generateMatrix(int n) {
vector<vector<int>> res(n, vector<int>(n));
int num = 1; // number to fill
for(int i = 0; i < n / 2; i++){
// reset row & col
// start from the left-top corner
int row = i;
int col = i;
// fix row, iterate col to n - i - 2
while(col < n - i - 1){
res[row][col] = num;
num++;
col++;
}
// fix col=n-i-1, row to n - i - 2
while(row < n - i - 1){
res[row][col] = num;
num++;
row++;
}
// fix row=n-i-1, col to i + 1
while(col > i){
res[row][col] = num;
num++;
col--;
}
// fix col=i, row to i + 1
while(row > i){
res[row][col] = num;
num++;
row--;
}
}
// if n is odd, fill the central element.
if(n % 2 != 0){
res[n / 2][n / 2] = n * n;
}
return res;
}
};
59. 螺旋矩阵 II
https://chrisnake11.github.io/blog/posts/coding/leecode/59-螺旋矩阵-ii/
作者
Zheyv
发布于
2025-07-15
许可协议
CC BY-NC-SA 4.0