算法竞赛002之蛇形填数
在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<=8
package practice;
import java.util.Scanner;
/**
* @author jins
* @date on 2019/1/12.
*/
public class Snake {
public static void main(String[] args)
{
// 定义二维数组
int [][]array ;
int n,x=0,y,count=1;
Scanner scanner = new Scanner(System.in);
n = scanner.nextInt();
array = new int[n][n];
// 找出第一个为1 的值
y=n-1;
array[x][y] = count;
// 使用while判断值,一直循环
// 当初想使用for , 没有while简便
while (count<n*n)
{
// 判断从上到下 走下一个走下去的元素是否越界和是否没有写入过值
// array[x+1][y]==0表示数组没有写如果值,可以写入,如果不等于0表示下个元素已经写如果值,不能再次写入
//x+1<n 表示 当n为4 是, x为2时还可以继续写入,当x为3时,已经填充完整,则不能再写
while (x+1<n && array[x+1][y]==0)
{
array[++x][y]= ++count;
}
// 判断从右向左走, y-1>=0 判断数组是否越界
//array[x][y-1]==0 判断前面一个元素是否写如果值,写如果则不写
while (y-1>=0 && array[x][y-1]==0)
{
array[x][--y]=++count;
}
// 判断从下往上走,判断数组是否越界和判断前面一个值是否写过
while (x-1>=0 && array[x-1][y]==0)
{
array[--x][y] = ++count;
}
// 判断从左往右写,判断是否越界和下面一个元素是否写过,当走过一圈之后,上下左右都有值,判断下个元素的值是否为0很有作用.
while (y+1<n && array[x][y+1]==0)
{
array[x][++y] = ++count;
}
}
for ( int i=0 ; i<n ; i++ )
{
for ( int j=0 ;j<n;j++ )
{
System.out.print(" " + array[i][j] + " ");
}
System.out.println("");
}
}
}
如果大家喜欢我的文章,可以关注我的微信公众号,后面会陆续更新!