Java模拟
import java.util.Scanner; public class Main { public static void main(String[] args) { Scanner sc = new Scanner(System.in); int n = sc.nextInt(); int cnt = 1; int l = 0, r = n - 1; int u = 0, d = n - 1; int[][] a = new int[n][n]; while (cnt <= n * n) { for (int j = l; j <= r; j++) {// 左到右 a[u][j] = cnt++; } u++;// 往下移动一行 for (int i = u; i <= d; i++) {// 上到下 a[i][r] = cnt++; } r--;// 往左移动一列 for (int j = r; j >= l; j--) {// 右到左 a[d][j] = cnt++; } d--;// 往上移动一行 for (int i = d; i >= u; i--) {// 下到上 a[i][l] = cnt++; } l++;// 往右移动一列 } for (int i = 0; i < a.length; i++) { for (int j = 0; j < a.length; j++) { System.out.print(a[i][j] + " "); } System.out.println(); } } }