蛇形填数

xiaoxiao2021-02-28  40

题目:在n*n方陈里填入1,2,...,n*n,要求填成蛇形。例如n=4时方阵为:

            10 11 12 1              9 16 13 2              8 15 14 3              7 6 5 4

          输入直接输入方陈的维数,即n的值。(n<=100)

          输出:输出结果是蛇形方阵。

解:

public class Main { public static void main(String[] args) { Scanner out = new Scanner(System.in); try { int x, y; int n = out.nextInt(); int[][] a = new int[10][10]; int num = a[x = 0][y = n - 1] = 1; while (num < n * n) { while (x + 1 < n && a[x + 1][y] == 0) a[++x][y] = ++num;// 向下走 while (y - 1 >= 0 && a[x][y - 1] == 0) a[x][--y] = ++num;// 向左走 while (x - 1 >= 0 && a[x - 1][y] == 0) a[--x][y] = ++num;// 向上走 while (y + 1 < n && a[x][y + 1] == 0) a[x][++y] = ++num;// 向右走 } for (int i = 0; i < n; i++) { for (int j = 0; j < n; j++) { System.out.print(a[i][j] + " "); } System.out.println(); } } finally { out.close(); } } }
转载请注明原文地址: https://www.6miu.com/read-2625951.html

最新回复(0)