|
|

楼主 |
发表于 2006-12-30 17:50:00
|
显示全部楼层
Re:一个应届毕业生的不归路。。。
也有可能是这样的规律:
// PBox.cpp : Defines the entry point for the console application.
/*
方格生成程序 by xmxoxo
题目:
如下图所示:把该图存于int data[10][10]中,请用代码实现
1 2 3 4 5
22 21 20 19 6
23 24 25 18 7
14 15 16 17 8
13 12 11 10 9
*/
#include "stdafx.h"
#include "stdlib.h"
#include "iostream.h"
#include "iomanip.h"
//最大100
int data[10][10];
int dire[4][2]={{0,-1},
{1,0},{0,1},{-1,0}};
void init()
{
int i,j;
for (i=0;i<10;i++)
{
for (j=0;j<10;j++)
{
data[j]=0;
}
}
}
//生成K方格
void gen(int k)
{
int x,y,n,d,ct,s;
x = -1; //初始坐标 -1,0
y = 0;
d = 1; //初始方向1
n = 1; //要填的数
ct = 0; //转弯计数器
s=0; //标志
while (n<=k*k)
{
//计算下一个位置
x = x + dire[d][0];
y = y + dire[d][1];
//判断超出
if ((x>=k||x<0)||(y>=k||y<0))
{
//,超出则退回原位
x = x - dire[d][0];
y = y - dire[d][1];
//转方向
d++;
if (d==4){d=0;}
s = 1;
continue;
}
//有数字
if (data[x][y]!=0)
{
//退回原位
x = x - dire[d][0];
y = y - dire[d][1];
//转方向
d++;
if (d==4){d=0;}
s=1;
continue;
}
//判断下一个位置
//为空,则填入数
if (data[x][y]==0)
{
data[x][y] = n;
n++;
if (s==1)
{
ct++;
if (ct==4){ct=0;}
s=0;
}
//如果是第3次转向
if (ct==3)
{
//填写一个数后立即转下一个方向
d++;
if (d==4){d=0;}
s=1;
}
continue;
}
}
}
//输出
void out(int k)
{
int i,j;
for (i=0;i<k;i++)
{
for (j=0;j<k;j++)
{
cout <<setw(4) << data[j];
}
cout<<endl;
}
}
int main()
{
int m;
while (1)
{
cout<< "请输入2-10之间的数[0退出]:";
cin>>m;
if (m==0)
{
break;
}
if (m<=10||m>=2)
{
init();
gen(m);
out(m);
}
}
return 0;
}
结果:
请输入2-10之间的数[0退出]:5
1 2 3 4 5
22 21 20 19 6
23 24 25 18 7
14 15 16 17 8
13 12 11 10 9
请输入2-10之间的数[0退出]:9
1 2 3 4 5 6 7 8 9
46 45 44 43 42 41 40 39 10
47 48 49 50 51 52 53 38 11
76 75 74 73 72 71 54 37 12
77 78 79 80 81 70 55 36 13
64 65 66 67 68 69 56 35 14
63 62 61 60 59 58 57 34 15
26 27 28 29 30 31 32 33 16
25 24 23 22 21 20 19 18 17
请输入2-10之间的数[0退出]:0
Press any key to continue
|
|