模拟
class Solution {
public int[][] generateMatrix(int n) {
/**
* 定义上下左右边界,每次循环一圈后都要缩小边界
* 从1开始赋值
*/
int[][] arr = new int[n][n];
int top = 0;
int bottom = n - 1;
int left = 0;
int right = n - 1;
int res = 1;
while (res <= n * n) {
/**
* 第一行
*/
for (int i = left; i <= right; i++) {
arr[top][i] = res++;
}
/**
* 缩小边界
*/
top++;
for (int i = top; i <= bottom; i++) {
arr[i][right] = res++;
}
right--;
for (int i = right; i>= left; i--) {
arr[bottom][i] = res++;
}
bottom--;
for (int i = bottom; i >= top; i--) {
arr[i][left] = res++;
}
left++;
}
return arr;
}
}
/**
* 时间复杂度 O(n^2)
* 空间复杂度 O(1)
*/
https://leetcode-cn.com/problems/spiral-matrix-ii/