流云

风驰影跃长 月映霜华裳
随笔 - 23, 文章 - 6, 评论 - 53, 引用 - 0

导航

<2008年11月>
2627282930311
2345678
9101112131415
16171819202122
23242526272829
30123456

留言簿(0)

随笔分类

随笔档案

文章分类

文章档案

相册

收藏夹

东观沧海

云散之处

搜索

最新评论

阅读排行榜

评论排行榜

细菌繁殖

细菌繁殖的题目 [所有相关帖子]

细菌繁殖的题目要求:
在一个800*600的棋盘中播种一个细菌,然后这个细菌开始繁殖。如果这个细菌的周围(8个方向)有地方适合他生存,则使该地方带菌,如此类推。
细菌的繁殖是有方向顺序的,最优先右方,然后优先级逆时针递减。也就是如果右面可以繁殖,繁殖右面,不可以就右上方,如果还不可以就上方、左上方。。。
细菌繁殖一次后,要等到它的子孙都不繁殖后才会继续繁殖,
求最后一个繁殖的细菌所在的位置。
书童 mochaojian 发表于 2006-6-8 21:10:52


#include <stdio.h>
#include 
<time.h>
#include 
<stdlib.h>
#include 
<memory.h>
#define WIDTH  800    //the map's width
#define HEIGHT 600    //the map's height

int map[WIDTH][HEIGHT];    //map,mark the path use integer
char to[8][2]={1,01,-10,-1-1,-1-1,0-1,10,11,1};// eight ways
typedef struct _pos
{
    unsigned x:   
12
;
    unsigned y:   
12
;
    unsigned way:  
3
;
}
POS;//define a position,x is row number and y is column number,way is which way to go.
POS path[WIDTH*HEIGHT];// the path

char check(int x,int y)    //check the next position(be out or have past)
{
    
if(x<0 || x>=WIDTH || y<0 || y>=HEIGHT ||
 map[x][y])
        
return 1;//invalid


    
return 0;//valid
}

void main()
{
    
int pos=0,cnt=1;//pos is the current position,cnt is the count of position having past.

    srand((unsigned)time(0));    
    POS last,first
={rand()%WIDTH,rand()%HEIGHT,0};//the last and first position

    
    
    memset(map,
0,sizeof(map));    //clear

    memset(path,0,sizeof(path));//clear
    path[0]=first;                //at first
    map[path[0].x][path[0].y] = 1;//pass number

    
while(1)
    
{        
        
for(int i=path[pos].way;i<8;i++)//8 ways

        {            
            
if(!check(path[pos].x+to[i][0],path[pos].y+to[i][1
]))
            
{
                path[pos].way 
= i;    //register the way having past

                pos++;
                path[pos].x 
= path[pos-1].x+to[i][0
];
                path[pos].y 
= path[pos-1].y+to[i][1
];                
                map[path[pos].x][path[pos].y] 
= cnt+1
;
                last
=path[pos];    //note the last

                cnt++;            //count
                i=0xffff;                            
                
break
;
            }

        }

        
if(cnt>=WIDTH*HEIGHT)    
            
break;//finished

        if(i<0xffff)
            pos
--;//run back

        printf("step %d : (%d,%d) pos=%d ",cnt-1,path[pos-1].x,path[pos-1].y,pos);        

    }

    
if(WIDTH<=28 && HEIGHT<=20 )   //too big number is not fit for print the map
    {
        
for(int k=0;k<HEIGHT;k++
)
        
{
            
for(int i=0;i<WIDTH;i++
)
            
{
                
                printf(
"%3d "
,map[i][k]);
            }

            printf(
" ");
        }

    }


    printf(
" the last is (%d,%d) ",last.x,last.y);//show the last
}

posted on 2006-06-08 22:57 流云 阅读(2295) 评论(0)  编辑 收藏

评论

标题  
姓名  
主页
验证码 *
内容   
  登录  使用高级评论  Top
[使用Ctrl+Enter键可以直接提交]