- import java.util.Arrays;
- import java.util.Scanner;
-
- // 给出一个不大于9的正整数n,输出n×n的蛇形方阵。
- public class Main {
- public static void main(String[] args) {
- Scanner sc = new Scanner(System.in);
- int n = sc.nextInt();
- int[][] a = new int[n][n];
- int total = 1;
- int x = 0;
- int y = 0;
- a[x][y] = 1;
- while (total
- while (y
1 && a[x][y+1] == 0) { - a[x][++y] = ++total;
- }
- while (x
1 && a[x+1][y] == 0) { - a[++x][y] = ++total;
- }
- while (y>0 && a[x][y-1] == 0) {
- a[x][--y] = ++total;
- }
- while (x>0 && a[x-1][y] == 0) {
- a[--x][y] = ++total;
- }
- }
- for (int i = 0; i < n; i++) {
- for (int j = 0; j < n; j++) {
- System.out.printf("%3d",a[i][j]);
- }
- System.out.println();
- }
- }
- }
