题目描述:
给你一个正整数 n
,生成一个包含 1
到 n2
所有元素,且元素按顺时针顺序螺旋排列的 n x n
正方形矩阵 matrix
。
示例 1:
输入:n = 3 输出:[[1,2,3],[8,9,4],[7,6,5]]
示例 2:
输入:n = 1 输出:[[1]]
提示:
1 <= n <= 20
代码(Java):
class Solution {
public int[][] generateMatrix(int n) {
int res[][] = new int[n][n];
int start = 0;
int number = 1;
int i, j;
int loop = 0;
while (loop++ < n / 2) {
for (j = start; j < n - loop; j++) {
res[start][j] = number;
number++;
}
for (i = start; i < n - loop; i++) {
res[i][j] = number;
number++;
}
for (; j >= loop; j--) {
res[i][j] = number;
number++;
}
for (; i >= loop; i--) {
res[i][j] = number;
number++;
}
start++;
}
if (n % 2 == 1) {
res[start][start] = number;
}
return res;
}
}
标签:LeetCode.59,start,int,res,矩阵,number,II,++,loop From: https://blog.csdn.net/weixin_63026062/article/details/136937714