蛇形数组

输入:4

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

代码:

import java.util.Scanner;
public class Main{
    public static void main(String[] args){
        Scanner scanner = new Scanner(System.in);
        while (scanner.hasNextInt()){
            int n = scanner.nextInt();
            fun(n);
        }
    }
    private static void fun(int n) {
        int[][] arr = new int[n][n];
        int num = 0;
        int x = 0, y = 0;
        while (num<n*n){
            while (y<n && arr[x][y]==0){
                arr[x][y++] = ++num;
            }
            x++; y--;
            while (x<n && arr[x][y]==0){
                arr[x++][y] = ++num;
            }
            x--; y--;
            while (y>=0 && arr[x][y]==0){
                arr[x][y--] = ++num;
            }
            x--; y++;
            while (x>0 && arr[x][y]==0){
                arr[x--][y] = ++num;
            }
            x++; y++;
        }
        for (int i = 0; i < n; i++) {
            for (int j = 0; j < n; j++) {
                System.out.print(arr[i][j] + "\t");
            }
            System.out.println();
        }
    }
}
posted @ 2016-04-05 20:33  小样儿1020  阅读(299)  评论(0编辑  收藏  举报