题目链接
解题思路
- 模拟法
- 每个颜色代表一条边,这里使用左闭右开原则,剩下的就是模拟了。
- 注意一下循环次数为
n/2,还有就是当n为奇数时要给最中心的点赋值

AC代码
class Solution {
public int[][] generateMatrix(int n) {
int loop = 0;
int[][] ans = new int[n][n];
int start = 0;
int count = 1;
int i, j;
while (loop++ < n / 2) {
for (j = start; j < n - loop; j++) {
ans[start][j] = count++;
}
for (i = start; i < n - loop; i++) {
ans[i][j] = count++;
}
for (; j >= loop; j--) {
ans[i][j] = count++;
}
for (; i >= loop; i--) {
ans[i][j] = count++;
}
start++;
}
if (n % 2 == 1) {
ans[start][start] = count;
}
return ans;
}
}
- 1
- 2
- 3
- 4
- 5
- 6
- 7
- 8
- 9
- 10
- 11
- 12
- 13
- 14
- 15
- 16
- 17
- 18
- 19
- 20
- 21
- 22
- 23
- 24
- 25
- 26
- 27
- 28
- 29
- 30
- 31
- 32