算法竞赛入门经典的java实现之蛇形填数->Demo18.java

版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/qq_36737934/article/details/80191809

在n*n的方阵里填入,1,2,3,4,~,n*n,要求填成蛇形。例如n=4时,方阵为:

10    11    12    1

  9    16    13    2

  8    15    14    3

  7      6      5    4

上面的方阵中,多余的空格只是为了便于观察,不必严格输出。n<=8。

下面贴出源码:

package cn.zimo.algorithm;

import java.util.Scanner;

/**
 * 蛇形填数
 * @author 子墨
 * @date 2018年5月2日 上午10:58:15
 */
public class Demo18 {
    public static void main(String[] args) {
        final int n=new Scanner(System.in).nextInt();
        int[][] a=new int[n][n];
        int x,y;
        int tot=1;
        x=0;
        y=n-1;
        //初始化
        for(int i=0;i<n;i++) {
            for(int j=0;j<n;j++) {
                a[i][j]=0;
            }
        }
        a[x][y]=1;
        while(tot<n*n) {
            while(x+1<n&&(a[x+1][y]==0)) {
                a[++x][y]=++tot;
            }
            while(y-1>=0&&(a[x][y-1]==0)) {
                a[x][--y]=++tot;
            }
            while(x-1>=0&&(a[x-1][y]==0)) {
                a[--x][y]=++tot;
            }
            while(y+1<n&&(a[x][y+1]==0)) {
                a[x][++y]=++tot;
            }
        }
        for(int i=0;i<n;i++) {
            for(int j=0;j<n;j++) {
                System.out.printf("%4d",a[i][j]);
            }
            System.out.println();
        }
    }
}


猜你喜欢

转载自blog.csdn.net/qq_36737934/article/details/80191809