参考一份和我思路一致,但是我不知道如何实现而另一位博主实现的文章
注释写在代码里
原文链接
import java.util.Scanner;
public class Spiralmatrix { //旋转方阵
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
System.out.println("请输入想打印的方阵阶数:");
int n = sc.nextInt();
int[][] array = new int[n][n];
System.out.println("请输入打印方式(顺时针请输入S/s,逆时针请输入N/n):");
char c = sc.next().charAt(0);
if (c=='S'||c=='s'){ //顺时针螺旋排列
clockwise(array,n);
}else{ //逆时针螺旋排列
anticlockwise(array,n);
}
for (int i = 0; i < array.length; i++) {
for (int j = 0; j < array[i].length; j++) {
System.out.printf("%4d",array[i][j]);
}
System.out.println();
}
}
public static void clockwise(int num[][],int n){
int boundary0 = n-1,boundary1 = n-1,boundary2 = 0,boundary3 = 1;//顺时针右下左上各自的边界
int direction = 0; //向方阵里填数的方向
int x = 0,y = 0; //方阵的行、列坐标
int k = 1; //方阵里要填的数
while(k<=n*n){ //方阵没满就循环填入
if (direction==0){ //右
num[x][y++] = k++;
if (y==boundary0){ //到达右边界
boundary0--; //右边界-1
direction = 1; //顺时针改变方向
}
}else if (direction==1){ //下
num[x++][y] = k++;
if (x==boundary1){ //到达下边界
boundary1--; //下边界-1
direction = 2; //顺时针改变方向
}
}else if (direction==2){ //左
num[x][y--] = k++;
if (y==boundary2){ //到达左边界
boundary2++; //左边界-1
direction = 3; //顺时针改变方向
}
}else{ //上
num[x--][y] = k++;
if (x==boundary3){ //到达上边界
boundary3++; //上边界-1
direction = 0; //顺时针改变方向
}
}
}
}
public static void anticlockwise(int num[][],int n){
int boundary0 = n-1,boundary1 = n-1,boundary2 = 0,boundary3 = 1;//逆时针下右上左各自的边界
int direction = 0; //向方阵里填数的方向
int x = 0,y = 0; //方阵的行、列坐标
int k = 1; //方阵里要填的数
while(k<=n*n){ //方阵没满就循环填入
if (direction==0){ //下
num[x++][y] = k++;
if (x==boundary0){ //到达下边界
boundary0--; //下边界-1
direction = 1; //逆时针改变方向
}
}else if (direction==1){ //右
num[x][y++] = k++;
if (y==boundary1){ //到达右边界
boundary1--; //右边界-1
direction = 2; //逆时针改变方向
}
}else if (direction==2){ //上
num[x--][y] = k++;
if (x==boundary2){ //到达上边界
boundary2++; //上边界-1
direction = 3; //逆时针改变方向
}
}else{ //左
num[x][y--] = k++;
if (y==boundary3){ //到达左边界
boundary3++; //左边界-1
direction = 0; //逆时针改变方向
}
}
}
}
}