紫书——蛇形填数
发布日期:2021-05-07 16:48:40 浏览次数:7 分类:原创文章

本文共 711 字,大约阅读时间需要 2 分钟。

#include<iostream>#include<string.h>//#include<time.h>#define maxn 20using 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++){               		 cout<<a[x][y]<<" ";		 }        		 cout<<endl;   	}    	system("pause");    	return 0;}

蛇形矩阵,1的位置在右上角,先判断,再移动,如果越界就回来。
!a[x][y]是因为初始化数组为0,如果碰到已经填好的数字了就缩回去,
x,y满足小于等于n的条件,表示n行n列。
++tot,先加1,再赋值。

上一篇:数学考试dp
下一篇:紫书——阶乘之和

发表评论

最新留言

关注你微信了!
[***.104.42.241]2025年03月31日 22时52分07秒