[Java] 纯文本查看 复制代码 package itcast;
import java.util.Scanner;
public class SpiralMatrix {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
System.out.print("请输入需要打印的螺旋方阵的维数:");
int n = sc.nextInt();
sc.close();
int[][] martix = matrix(n);
for (int i = 0; i < n; i++) {
for (int j = 0; j < n; j++) {
System.out.print(martix[i][j]+"\t");
}
System.out.println();
System.out.println();
System.out.println();
}
}
private static int[][] matrix(int n) {
int[][] martix = new int[n][n];
int number = 1;
int a = 0; int b = n;
for (int i = 0; i < n-2; i++) {
for (int y = a; y < b; y++) {
martix[a][y] = number;
number++;
}
for (int x = a+1; x < b - 1; x++) {
martix[x][b-1] = number;
number++;
}
for (int y = b-1; y >= a; y--) {
martix[b-1][y] = number;
number++;
}
for (int x = b - 2; x >= a+1; x--) {
martix[x][a] = number;
number++;
}
if((n%2!=0)) {
martix[n/2][n/2] = n*n;
}
a++;
b--;
}
return martix;
}
}
|