醉酒蟑螂的随机漫步
星期四, 6月 5th, 2008C语言太久没碰,调试花了差不多一个晚上。程序编译环境:Fedora 8 gcc 4.1.2
在矩形房间里,地面铺有N*M块瓷砖,一只醉酒的蟑螂在一块指定的瓷砖上随机漫步到相邻的令一块瓷砖上,求它至少接触每块瓷砖一次花费的时间。
实验按12*12的环境进行
- #include <stdio.h>
- #include <stdlib.h>
- #include <time.h>
- //最大步数限制
- #define MAX_STEP_ON 65535
- #define MAX_X 12
- #define MAX_Y 12
- //房间的磁砖
- unsigned arr[MAX_X][MAX_Y];
- //相邻磁砖的位移
- const int stepx[]={-1,0,1,1,1,0,-1,-1};
- const int stepy[]={1,1,1,0,-1,-1,-1,0};
- //记录当前位置
- int current[2];
- //步数
- unsigned stepcount=0;
- int main(){
- int isclean=clean();
- srand((unsigned)time(NULL));
- walk();
- }
- int clean(){
- int x=0,y=0;
- for(x;x<MAX_X;x++){
- for(y;y<MAX_Y;y++){
- arr[x][y]=0;
- }
- }
- printf("please input the begin Abscissa\n");
- scanf("%d",¤t[0]);
- printf("please input the begin Ordinate\n");
- scanf("%d",¤t[1]);
- arr[current[0]][current[1]]+=1;
- return 1;
- }
- int walk(){
- if(check()==0){
- int step=rand()%9;
- int nextx=current[0]+stepx[step];
- int nexty=current[1]+stepy[step];
- if(stepcount<MAX_STEP_ON){
- printinfo(0);
- exit(0);
- }
- if(nextx>=0&&nextx<=MAX_X-1&&nexty>=0&&nexty<=MAX_Y-1&&arr[nextx][nexty]<65535){
- ++arr[nextx][nexty];
- ++stepcount;
- //printf("%d,%d\t%d\n",current[0],current[1],step);
- current[0]=nextx;
- current[1]=nexty;
- }
- walk();
- }
- else{
- printinfo(1);
- exit(0);
- }
- }
- int check(){
- int x,y;
- for(x=0;x<MAX_X;x++){
- for(y=0;y<MAX_Y;y++){
- if(arr[x][y]==0)
- return 0;
- }
- }
- return 1;
- }
- int printinfo(int success){
- if(!success){
- printf("It's not Complete walk around the room\n");
- }
- printf("the bug total walk:%d steps\n\n",stepcount);
- int x,y;
- for(x=0;x<MAX_X;x++){
- for(y=0;y<MAX_Y;y++){
- if(y==0)
- printf("\n%d\t",arr[x][y]);
- else
- printf("%d\t",arr[x][y]);
- }
- }
- }
以下省略图N张


