Given an integer n, generate a square matrix filled with elements from 1 to n2 in spiral order.
For example,
Given n = 3,
You should return the following matrix:
[
1, 2, 3 ,
8, 9, 4 ,
7, 6, 5
]
public int[][] generateMatrix(int n) {
if (n <= 0) {
return new int[0][0];
}
int[][] matrix = new int[n][n];
int num = 1;
int startx = 0, endx = n - 1;
int starty = 0, endy = n - 1;
while (startx <= endx && starty <= endy) {
// 上边的行,从左向右
for (int y = starty; y <= endy; y++) {
matrix[startx][y] = num++;
}
// 右边的列,从上到下
for (int x = startx + 1; x <= endx; x++) {
matrix[x][endy] = num++;
}
// 如果行或列遍历完,则退出循环
if (startx == endx || starty == endy) {
break;
}
// 下边的行,从右向左
for (int y = endy - 1; y >= starty; y--) {
matrix[endx][y] = num++;
}
// 左边的列,从下到上
for (int x = endx - 1; x >= startx + 1; x--) {
matrix[x][starty] = num++;
}
startx++;
starty++;
endx--;
endy--;
}
return matrix;
}
原创声明:本文系作者授权腾讯云开发者社区发表,未经许可,不得转载。
如有侵权,请联系 cloudcommunity@tencent.com 删除。
原创声明:本文系作者授权腾讯云开发者社区发表,未经许可,不得转载。
如有侵权,请联系 cloudcommunity@tencent.com 删除。