直接上代码:
import java.util.Scanner;
public class Main {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
int n = sc.nextInt();
sc.close();
int row = 0, col = 0;
int top = 0, left = -1, right = n - 1, bottom = n - 1;
int[][] arr = new int[n][n];
int num = 0;
while(num<n*n){
for (int j = ++left; j <= right; j++) {
col = j;
arr[row][col] = ++num;
}
for (int k = ++top; k <= bottom; k++) {
row = k;
arr[row][col] = ++num;
}
for (int j = --right; j >= left; j--) {
col = j;
arr[row][col] = ++num;
}
for (int k = --bottom; k >= top; k--) {
row = k;
arr[row][col] = ++num;
}
}
for(int i=0; i<n;i++){
for(int j=0; j<n;j++){
System.out.print(arr[i][j]+" ");
}
System.out.println();
}
}
}
输入n=6;
输出结果应该为:
1 2 3 4 5 6
20 21 22 23 24 7
19 32 33 34 25 8
18 31 36 35 26 9
17 30 29 28 27 10
16 15 14 13 12 11
Game Over