码迷,mamicode.com
首页 > 其他好文 > 详细

每日一水-----蛇形填数

时间:2015-05-20 13:23:05      阅读:111      评论:0      收藏:0      [点我收藏+]

标签:

描述:  

在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

/***************************************************************************/

import java.util.Scanner;

public class Main {
	public static void main(String[] args) {
		Scanner sc = new Scanner(System.in);
		int n = sc.nextInt();
		int[][] arr = new int[n][n];
		
		for(int i=0;i<n;i++){
			for(int z=0;z<n;z++){
				arr[i][z] = 0;
			}
		}
		
		int number = 1;
		
		Direction d = Direction.down;
		
		int x=0;
		int y=n-1;
		while(number < n*n){
			if(d == Direction.down){
				if(x == n-1 || arr[x+1][y] != 0){
					d = Direction.left;
				}else{
					arr[x][y]= number;
					number ++ ;
					x++;
				}
			}
			
			if(d == Direction.left){
				if(y==0 || arr[x][y-1] != 0){
					d = Direction.up;
				}else{
					arr[x][y]= number;
					number ++ ;
					y--;
				}
			}
			
			if(d == Direction.up){
				if(x == 0 || arr[x-1][y] != 0){
					d = Direction.right;
				}else{
					arr[x][y]= number;
					number ++ ;
					x--;
				}
			}
			
			if(d == Direction.right){
				if(y == n-1 || arr[x][y+1] !=0){
					d = Direction.down;
				}else{
					arr[x][y]= number;
					number ++ ;
					y++;
				}
			}
		}
		for(int i=0;i<n;i++){
			for(int z=0;z<n;z++){
				if(arr[i][z] == 0){
					arr[i][z] = n*n;
				}
				System.out.print(arr[i][z]+" ");
			}
			System.out.println();
		}
	}
}

enum Direction{
	down,left,up,right
}

只要存数字时按照方向来就存就行了,如果到边界或者下一个有数字了就让他转向存.这里有个问题,如果把最后一个数字也在循环里面放进去的话 就进入无限循环了..不知道怎么跳出,干脆就在输出的时候把这个数字替换掉了...

每日一水-----蛇形填数

标签:

原文地址:http://my.oschina.net/u/2358837/blog/417156

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!