题目:力扣
思路:
n =3 时,我们需要循环1次,
n =4 时,我们需要循环2次
所以这里 循环loop = n / 2次。
代码:
class Solution {
public int[][] generateMatrix(int n) {
int loop = 0;
int res[][] = new int[n][n];
int start = 0;
int count = 1;
int x = 0;
int y = 0;
while (loop++ < n/2) {
// 顶部
// 左至右
for (y = start; y < n - loop; y++) {
res[start][y] = count++;
}
// 左侧
// 上至下
for (x = start; x < n - loop; x++) {
res[x][y] = count++;
}
// 底部
// 右至左
for (; y >= loop; y--) {
res[x][y] = count++;
}
// 下至上
for (; x >= loop; x--) {
res[x][y] = count++;
}
start++;
}
if (n % 2 == 1) {
res[start][start] = count;
}
return res;
}
}