Fork me on GitHub

蛇形填数

题目描述:

在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)

输出描述:

输出结果是蛇形方阵。

样例输入:

3

样例输出:

7 8 1
6 9 2
5 4 3



原理:创建一个二维数组,将数组清零,用a[i][j]==0判断该位置是否已填数,用x,y记录下一个数的坐标,t记录填入的数字。

1
import java.util.Arrays; 2 import java.util.Scanner; 3 4 public class SnackSquare { 5 public static void main(String[] args) { 6 Scanner sc = new Scanner(System.in); 7 int n = sc.nextInt(); 8 int[][] a = new int[n][n]; 9 for (int[] temp : a) 10 Arrays.fill(temp, 0); 11 int t = 1, x = 0, y = n - 1; 12 a[0][n - 1] = t; 13 while (t < n * n) { 14 while (x + 1 < n && a[x + 1][y] == 0) 15 a[++x][y] = ++t; 16 while (y - 1 >= 0 && a[x][y - 1] == 0) 17 a[x][--y] = ++t; 18 while (x - 1 >= 0 && a[x - 1][y] == 0) 19 a[--x][y] = ++t; 20 while (y + 1 < n && a[x][y + 1] == 0) 21 a[x][++y] = ++t; 22 } 23 for (int i = 0; i < n; i++) { 24 for (int j = 0; j < n; j++) { 25 System.out.print(a[i][j] + " "); 26 } 27 System.out.println(); 28 } 29 sc.close(); 30 } 31 }

 



posted on 2019-06-19 10:16  Co3y  阅读(277)  评论(0编辑  收藏  举报

导航