题干
给定一个正整数 n,生成一个包含 1 到 n2 所有元素,且元素按顺时针顺序螺旋排列的正方形矩阵。
示例:
输入: 3
输出:
[
[ 1, 2, 3 ],
[ 8, 9, 4 ],
[ 7, 6, 5 ]
]
想法
思路和螺旋矩阵相同,要点就是方向和边界
Java代码
public class GenerateMatrix {
public int[][] generateMatrix(int n) {
int x = 0;
int y = 0;
boolean[][] flag = new boolean[n][n];
int[][] res = new int[n][n];
//0123 右下左上
int direct = 0;
int trm = 1;
while (x >= 0 && y >= 0 && x < n && y < n) {
if (flag[x][y]) {
break;
}
res[x][y] = trm;
trm++;
flag[x][y] = true;
switch (direct) {
case 0:
if (y == n - 1 || flag[x][y + 1]) {//走到右边界,注意有新的右边界
x++;//就向下走一步,并且改变方向
direct = 1;
} else {
y++;
}
break;
case 1:
if (x == n - 1 || flag[x + 1][y]) {//走到下边界注意有新的下边界
y--;
direct = 2;
} else {
x++;
}
break;
case 2:
if (y == 0 || flag[x][y - 1]) {//走到左边界注意有新的左边界
x--;//向上走
direct = 3;
} else {
y--;
}
break;
case 3:
if (x == 0 || flag[x - 1][y]) {
y++; //如果向上走到头就右走
direct = 0;
} else {
x--;
} //向上走
break;
}
}
return res;
}
public static void main(String[] args) {
GenerateMatrix generateMatrix = new GenerateMatrix();
int[][] test = generateMatrix.generateMatrix(3);
for (int i = 0; i < 3; i++) {
System.out.print("\n");
for (int j = 0; j < 3; j++) {
System.out.print(test[i][j]);
}
}
}
}