在n*m的方阵里填入1,2,3,...,要求添成蛇形。其中m,n<=10。例如n=3,m=4时的方阵为:
1-2-3-4
|
0-1-2 5
| |
9-8-7-6
填数方向为左下右上。且填数为从0~9循环,即是9过了又是0
1-2-3-4
|
0-1-2 5
| |
9-8-7-6
填数方向为左下右上。且填数为从0~9循环,即是9过了又是0
Description
多组数据,两个整数n,m(0 < n,m < 11)n为排数,m为列数.
Input
填好的方阵,每两组测试数据之间有一个空行。
Output
1
|
5 4
|
Sample Input
1
2
3
4
5
6
|
0123
3454
2965
1876
0987
|
Sample Output
#include<stdio.h>
#include<math.h>
#include<string.h>
int main()
{
int n, m;
int a[100][100];//用来存数据
int vis[100][100];//判断每个点是否走过
int p = 0;
while (scanf("%d %d", &n, &m) != EOF)//n行m列
{
if (p != 0)//格式要求每两组测试数据之间有一个空行。
printf("\n");
int count = 1;//统计标记点的个数
int temp = 0;
int x, y;//用来标识遍历到何处
x = 0, y = 0;//从(0,0)这个点开始
memset(vis, 0, sizeof(vis));//数组初始化函数
a[x][y] = temp;//标记第一个数
vis[x][y] = 1;
while (count < n*m)//当标记点个数>n*m之后,对数组处理完成,跳出循环
{
while (y + 1 < m && !vis[x][y + 1])//先向右走
{
temp++;
if (temp > 9)//如果temp>9 则temp=0
temp = 0;
a[x][++y] = temp;
vis[x][y] = 1;//标记此点走过
count++;
}
while (x + 1 < n && !vis[x + 1][y])//想下走
{
temp++;
if (temp > 9)
temp = 0;
a[++x][y] = temp;
vis[x][y] = 1;
count++;
}
while (y - 1 >= 0 && !vis[x][y - 1])//向左走
{
temp++;
if (temp > 9)
temp = 0;
a[x][--y] = temp;
vis[x][y] = 1;
count++;
}
while (x - 1 >= 0 && !vis[x - 1][y])//向上走
{
temp++;
if (temp > 9)
temp = 0;
a[--x][y] = temp;
vis[x][y] = 1;
count++;
}
}
for (int i = 0;i < n;i++)//最后输出就可以了
{
for (int j = 0;j < m;j++)
{
printf("%d", a[i][j]);
}
printf("\n");
}
p = 1;
}
return 0;
}