一、题目
二、思路
设定四个边界,由外向内一层层模拟生成数字
三、代码实现
public int[][] generateMatrix(int n) {
int[][] res = new int[n][n];
int num = 1;
int left = 0, right = n - 1, up = 0, bottom = n - 1;
while (left < right && up < bottom) {
//左到右
for (int i = left; i <= right; i++) {
res[up][i] = num++;
}
//上到下
for (int i = up + 1; i <= bottom; i++) {
res[i][right] = num++;
}
//右到左
for (int i = right - 1; i >= left; i--) {
res[bottom][i] = num++;
}
//下到上
for (int i = bottom - 1; i > up; i--) {
res[i][left] = num++;
}
left++;
right--;
up++;
bottom--;
}
return res;
}