蛇形填数
时间限制:
3000 ms | 内存限制:
65535 KB
难度:
3
-
描述
-
在n*n方陈里填入1,2,...,n*n,要求填成蛇形。例如n=4时方陈为:
10 11 12 1
9 16 13 2
8 15 14 3
7 6 5 4
/*
此题按照题意进行模拟就可以了,注意点一定要先判断能否前进,能在前进,不能就不要往前执行了,因为前进后
后撤的难度更大
*/
#include <iostream>
#include <iomanip>
#include<cstring>
using namespace std;
int a[100][100];
int main(){
int n,count,x,y;
cin>>n;
memset(a,0,sizeof(a)); //初始化为0
count = a[x=0][y=n-1] = 1;
while(count<n*n){
while(x+1<n && !a[x+1][y]) a[++x][y]=++count;
while(y-1>=0 &&!a[x][y-1]) a[x][--y]=++count;
while(x-1>=0 &&!a[x-1][y]) a[--x][y]=++count;
while(y+1<n &&!a[x][y+1]) a[x][++y] =++count;
}
for(x=0;x<n;x++){ //输出
for(y=0;y<n;y++){
cout<<setw(5)<<a[x][y];
}
cout<<endl;
}
return 0;
}