题目描述
在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>
int num[250][250];
int book[250][250];
int main(){
int n;
scanf("%d",&n);
int cnt=1,i=0,j=n-1;
num[i][j]=1;
book[i][j]=1;
while(cnt<n*n){
while(i+1<n&&!book[i+1][j]){ //向下
book[i+1][j]=1;
num[++i][j]=++cnt;
}
while(j-1>=0&&!book[i][j-1]){ //向左
book[i][j-1]=1;
num[i][--j]=++cnt;
}
while(i-1>=0&&!book[i-1][j]){ //向上
book[i-1][j]=1;
num[--i][j]=++cnt;
}
while(j+1<n&&!book[i][j+1]){ //向右
book[i][j+1]=1;
num[i][++j]=++cnt;
}
}
for(i=0;i<n;i++){
for(j=0;j<n-1;j++)
printf("%d ",num[i][j]);
printf("%d\n",num[i][j]);
}
return 0;
}
1346

被折叠的 条评论
为什么被折叠?



