題目:在n*n方陣裏填入1,2,3,...,n*n,要求填成蛇形,n<=8。例如n=4時方陣爲:
10 11 12 1
9 16 13 2
8 15 14 3
7 6 5 4
分析:類比數學中的矩陣,我們可以用一個二維數組去存儲題目中的方陣。只需聲明一個int a[MAX][MAX],就可以獲得一個大小爲MAX*MAX的方陣。
#include
#include
#define MAX 10
using namespace std;
int a[MAX][MAX];
int main(){
int tot=0;
int x,y,n;
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