描述
在n*n方陈里填入1,2,...,n*n,要求填成蛇形。例如n=4时方陈为:
10 11 12 1
9 16 13 2
8 15 14 3
7 6 5 4
10 11 12 1
9 16 13 2
8 15 14 3
7 6 5 4
-
输入
- 直接输入方陈的维数,即n的值。(n<=100) 输出
- 输出结果是蛇形方陈。 样例输入
-
3
样例输出 -
7 8 1 6 9 2 5 4 3
#include<stdio.h>
#include<string.h>
int book[100][100],str[100][100];
int a[4][2]= {0,1,1,0,0,-1,-1,0,},n,p;
void dfs(int x,int y,int s,int k)
{
int tx,ty,i,j;
if(s==n*n)
{
for(i=0; i<n; i++)
{
for(j=0; j<n; j++)
printf("%d ",str[i][j]);
printf("\n");
}
return ;
}
for(p=k;p<8;p++)
{
tx=x+a[p%4][0];
ty=y+a[p%4][1];
k=p%4;
if(tx<0||ty<0||tx>=n||ty>=n||book[tx][ty]==1)continue;
book[tx][ty]=1;
str[tx][ty]=s+1;
dfs(tx,ty,s+1,k);
}
}
int main()
{
while(~scanf("%d",&n))
{
p=0;
memset(book,0,sizeof(book));
str[0][n-1]=1;
book[0][n-1]=1;
dfs(0,n-1,1,0);
}
return 0;
}