蛇形矩阵
#include<stdio.h>
#include<string.h>
const int maxn = 12;//the size of the maze
int a[ maxn ][ maxn ];
const int dx[]={0,1,0,-1};
const int dy[]={1,0,-1,0};
bool inside( int x,int y,int n ){
if( x>=0&&x<n&&y>=0&&y<n ) return true;
else return false;
}
int main(){
int ca;
scanf("%d",&ca);
for( int t=0;t<ca;t++ ){
int n;
scanf("%d",&n);
printf("case #%d:\n",t);
memset( a,0,sizeof( a ) );
/*
for( int i=0;i<=n;i++ ){
a[ i ][ n ] = -1;
a[ n ][ i ] = -1;
}
*/
int cnt = 1;
int pos = 0;
int x,y;
x = y = 0;
int tx,ty;
tx=ty=0;
while( cnt<=n*n ){
if( inside( tx,ty,n )==true&&a[ tx ][ ty ]==0 ){
a[ tx ][ ty ] = cnt++;
x=tx,y=ty;
}
else{
pos++;
pos%=4;
}
tx=x+dx[pos],ty=y+dy[pos];
//x += dx[ pos ],y += dy[ pos ];
}
for( int i=0;i<n;i++ ){
for( int j=0;j<n;j++ ){
if( j==0 ) printf("%d",a[i][j]);
else printf(" %d",a[i][j]);
}
printf("\n");
}
}
return 0;
}
keep moving...

浙公网安备 33010602011771号