//输出 n=5 的螺旋方阵,下面是获取方法
public static void getScrew(int n) {
int[][] arr = new int[n][n];//创建二维数组
int temp = 0;//数组中元素的初始值
//计算螺旋数组转的圈数x
int x;
if (n%2==0) {
x = n/2;
} else {
x = n/2+1;
}
//思路创建二维数组arr[a][b]
for (int y = 0; y < x; y++) {//以圈数为循环
//上循环,从左到右;数组arr[y][a]----y不变,a++
for (int a = y; a < n-y ; a++) {
temp++;
arr[y][a] = temp;
}
//右循环,从上到下;数组arr[b][n-y-1]----b++;n-y-1不变
for (int b = y+1; b < n-y-1; b++) {
temp++;
arr[b][n-y-1] = temp;
}
//下循环,从右到左;数组arr[n-y-1][c]----n-y-1不变;c--
for (int c = n-y-1; c > y; c--) {
temp++;
arr[n-y-1][c] = temp;
}
//左循环,从下到上;数组arr[d][y]----d--;y不变
for (int d = n-y-1; d > y; d--) {
temp++;
arr[d][y] = temp;
}
}
//对数组进行输出
for (int i = 0; i < arr.length; i++) {
for (int j = 0; j < arr.length; j++) {
System.out.print(arr[i][j]+"\t");
}
System.out.println();
}
} |