本文共 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,再赋值。
转载地址:http://cqdr.baihongyu.com/