力扣59题
题目描述:
给你一个正整数
n
,生成一个包含1
到n^2
所有元素,且元素按顺时针顺序螺旋排列的n x n
正方形矩阵matrix
。
![image.png](https://img-home.csdnimg.cn/images/20230724024159.png?origin_url=https%3A%2F%2Fs2.loli.net%2F2024%2F08%2F12%2FRP6g4EM3qbAprzd.png&pos_id=img-YYymfhFf-1723767605784%29)
**题解思路:**模拟题。需要模拟顺时针转圈的逻辑,重点是对上下左右边界的处理,定义好最边的值要不要读取是关键。
class Solution {
public int[][] generateMatrix(int n) {
int[][] res = new int[n][n];
int count = 1;
int x = 0;
int y = 0;
int i, j;
int offset = 1;// 每次最后一个不做处理
int loop = 1;
while (loop <= n / 2) {
// 模拟 从左到右
for (j = y; j < n - offset; j++) {
res[x][j] = count++;
}
// 模拟 从上到下
for (i = x; i < n - offset; i++) {
res[i][j] = count++;
}
// 模拟 从右到左
for (; j > y; j--) {
res[i][j] = count++;
}
// 模拟 从下到上
for (; i > x; i--) {
res[i][j] = count++;
}
// 转完一圈后,更新参数
loop++;
offset++;
x++;
y++;
}
// 如果秩是奇数的话,单独处理最中间的值
if (n % 2 == 1) {
res[x][y] = count++;
}
return res;
}
}