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

提示:
1 <= n <= 20
解题思路:
1.生成一个 n x n 的矩阵,矩阵中填充从 1 到 n*n 的数字,以顺时针螺旋顺序填充
2.定义矩阵的左、右、上、下边界
3.当左边界不超过右边界,且上边界不超过下边界时,进行循环
4.按照从左到右填充上边界,从上到下填充右边界
5.如果矩阵大于1x1,则从右到左填充下边界和从下到上填充左边界
6.更新边界,缩小矩阵

完整代码
class Solution {
/**
* 生成一个 n x n 的矩阵,矩阵中填充从 1 到 n*n 的数字,以顺时针螺旋顺序填充
*
* @param n 矩阵的行数和列数
* @return 填充了数字的矩阵
*/
public int[][] generateMatrix(int n) {
// 初始化一个 n x n 的矩阵
int[][] res = new int[n][n];
// 定义矩阵的左、右、上、下边界
int left = 0;
int right = n-1;
int top = 0;
int bottom = n-1;
// 从1开始填充矩阵
int num = 1;
// 当左边界不超过右边界,且上边界不超过下边界时,进行循环
while (left <= right && top <= bottom){
// 从左到右填充上边界
for (int column = left; column <= right; column++) {
res[top][column ] = num;
num++;
}
// 从上到下填充右边界
for (int row = top+1; row <= bottom; row++){
res[row][right] = num;
num++;
}
// 如果矩阵大于1x1,则从右到左填充下边界和从下到上填充左边界
if (left < right && top < bottom) {
for (int column = right - 1; column > left; column--) {
res[bottom][column] = num;
num++;
}
for (int row = bottom; row > top; row--) {
res[row][left] = num;
num++;
}
}
// 更新边界,缩小矩阵
left++;
right--;
top++;
bottom--;
}
// 返回填充完成的矩阵
return res;
}
}

浙公网安备 33010602011771号