算法竞赛入门经典 第3章 数组和字符串 学习笔记 2

蛇形填数
蛇形填数:在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。
这个肯定是要用到二维数组的
用到了预判,先判断再向上下左右运动会不会越界以及将要运动到的地方是不是已经填了数

#include<iostream>
#include<cstring>
#define maxn 20
using namespace std;
int a[maxn][maxn];
int main()
{
	int n,x,y,tot=0;
	cin>>n;
	memset(a,0,sizeof(a)); //初始化
	tot=a[x=0][y=n-1]=1;
	while(tot<n*n)
	{
                //这几个的顺序不能动,所有的都是先向下再向左。。。
		while(x+1<n&&!a[x+1][y])  a[++x][y]=++tot;           //因为是预判,所以填的时候需要加一
		while(y-1>=0&&!a[x][y-1])  a[x][--y] = ++tot;    
		while(x-1>=0 && !a[x-1][y]) a[--x][y] = ++tot; 
		while(y+1<n && !a[x][y+1]) a[x][++y] = ++tot;
	} 
	for(x = 0; x < n; x++) 
	{ 
		for(y = 0; y < n; y++) 
			printf("%3d", a[x][y]);  //留几个空格,显得整齐
		printf("\n"); 
	}
	return 0;
}

猜你喜欢

转载自www.cnblogs.com/serendipity-my/p/12633028.html