创建蛇形数组

来源:互联网 发布:理正岩土局部搜索算法 编辑:程序博客网 时间:2024/04/29 10:13
/*  在n*n方阵中输入1....n*n,要求数据呈蛇形,先下到底再转去左,到底转上,到顶后再转右,形成蛇形*/#include<string.h>using namespace std;#define Max 10int a[Max][Max];int main(){int n,x,y,tot=0;cout<<"input n: "<<endl;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;//右}cout<<"show the result: "<<endl;for(x=0;x<n;x++){for(y=0;y<n;y++)cout<<a[x][y]<<'\t';         cout<<endl;}return 0;}

0 0
原创粉丝点击