59.螺旋矩阵 II
标签:数组、矩阵、模拟
难度:中等
描述:给定一个正整数 n。
要求:要求生成一个包含 1 到 n2 所有元素,且元素按顺时针顺序螺旋排列的 n x n 正方形矩阵 matrix 。
说明:
1 <= n <= 20
示例:
输入:n = 3
输出:[[1,2,3],[8,9,4],[7,6,5]]
思路1
这是一道模拟顺时针画矩阵的题目,一轮的螺旋排列可以分为4个阶段:左到右、上到下、右到左、下到上。以从左到右为例,我们遍历采取左闭右开区间赋值,这样下个阶段的边界条件也比较清晰。
更详细的信息见代码内容。

public int[][] generateMatrix(int n) {
int[][] res = new int[n][n];
// loop控制螺旋排列的次数
int loop = n / 2;
int startx, starty, offset;
// startx和starty是每一轮螺旋排列的起点坐标
startx = starty = 0;
// offset控制边界。每当向一个方向赋值时候,构成一闭一开区间。
offset = 1;
// 当loop是奇数时,矩阵中间的元素需要单独赋值
int mid = n / 2;
// count用于给矩阵元素赋值
int count = 1;
int i, j;
while (loop > 0){
i = startx;
j = starty;
// 一轮的螺旋排列
// 1.从左到右赋值.左闭右开区间
for (; j < n - offset; j++){
res[i][j] = count++;
}
// 2.从上到下赋值.一开一闭区间
for (; i < n - offset; i++){
res[i][j] = count++;
}
// 3.从右到左赋值.一开一闭区间
for (; j > starty; j-- ){
res[i][j] = count++;
}
// 4.从下到上赋值.一开一闭区间
for (; i > startx; i--){
res[i][j] = count++;
}
// 更新参数
startx++;
starty++;
loop--;
offset++;
}
// 当loop是奇数时,矩阵中间的元素需要单独赋值
if (n % 2 == 1){
res[mid][mid] = count;
}
return res;
}思路2
本题采用 54.螺旋矩阵 上下左右边界实现控制访问。
public int[][] generateMatrix(int n) {
int[][] res = new int[n][n];
// 定义左右上下边界
int left = 0, right = n - 1, top = 0, bottom = n - 1;
int i = 0, j = 0;
int count = 1;
while (count <= n*n){
// 从左到右
for (j = left; j <= right; j++){
res[top][j] = count++;
}
if (++top > bottom)
break;
// 从上到下
for (i = top; i <= bottom ; i++){
res[i][right] = count++;
}
if (--right < left)
break;
// 从右到左
for (j = right; j >= left ; j--){
res[bottom][j] = count++;
}
if (--bottom < top)
break;
// 从下到上
for (i = bottom; i >= top; i--){
res[i][left] = count++;
}
if (++left > right)
break;
}
return res;
}
评论区