2045:【例5.13】蛇形填数
在n×n方阵里填入1,2,3,…,n×n,要求填成蛇形。例如n=4时方阵为:
10 11 12 1
9 16 13 2
8 15 14 3
7 6 5 4
上面的方阵中,多余的空格只是为了便于观察规律,不必严格输出,n<=8。
只需要声明int a[max][max],就可以获得一个大小为max * max的方阵。在声明时,两维的大小不必相同,因此也可以声明int a[30][50]这样的数组,第一维下标的范围是0,1,2,3,4,,29,第二维下标范围是0-49。
让我们从1开始依次填写。
设“笔”的坐标为(x,y),则一开始x=0,y=n-1,也就是第0行,第n-1列(行列的范围是0到n-1,没有第n列)。移动的轨迹是:下下下左左左上上上右右下下左上。总之,先是下,到了不能填了为止,然后是左,接着是上,最后是右。
不能填,就是指再走就出界了,或者再走就要走到以前填过的格子。如果我们把所有的格子,初始化为0,就可以很方便的加以判断。
#include<bits/stdc++.h>using namespace std;int a[25] [25];intmain(){ int n;cin >> n; int x,y,tot; memset(a,0,sizeof(a)); tot=a[x=0][y=n-1]=1; while(tot<n*n){ // x+1=n时越界,退出循环,需要x+1<n // a[x+1][y]!=0,退出循环,需要 a[x+1][y]==0 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){ cout << a[i][j] << " "; } cout << endl; } return 0;}