(33)蛇形填数

来源:互联网 发布:js数组lastindexof 编辑:程序博客网 时间:2024/05/21 19:35

描述
在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 16 9 25 4 3

/** *  */package test;import java.io.BufferedReader;import java.io.IOException;import java.io.InputStreamReader;/** * @author Administrator * */public class Test_33 {/** * 蛇形填数 * 在n*n方陈里填入1,2,...,n*n,要求填成蛇形。例如n=4时方陈为: * 10 11 12 1 * 9 16 13 2 * 8 15 14 3 * 7 6 5 4 * @param args * @throws IOException  */public static void main(String[] args) throws IOException {BufferedReader br = new BufferedReader(new InputStreamReader(System.in));int n = Integer.parseInt(br.readLine());int[][] a = new int[n][n];for(int i = 0; i < n; i++){for(int j = 0; j < n; j++){a[i][j] = 0;}}int x = 0;int y = n-1;int num = 1;a[x][y] = 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] + "\t");if(j == n-1){System.out.println("");}}}}}






0 0