zoj 2165 Red and Black (BFS)

16 篇文章 0 订阅

雨不停的下了好几天了,烦躁的心也渐渐平静下来,耳畔的轻音乐依旧。。。。

静下心来做题,还算不错,有一道不会,先放过去了,这道题不快不慢得,一次就AC,感觉很好,呵呵。。。

思路:

     1.也算是队列吧,只是入队和出队时,把坐标也一起随进去了;

     2.b数组用来标记这块砖是否已经走过,如果走过一遍了,就不再走了;

     3.出队时用了两个指针,这样可以把元素的俩坐标同时带出来;

还有点想法:

    内while循环中,其实是四个相同的结构用了四次,可以考虑写成四个函数,然后调用四次,这样就又可以简化代码了。。。。。

#include<stdio.h>
#include<string.h>
typedef struct 
{  
    char s[5000];
    int s1[5000];
    int s2[5000];
}queue;
queue que;
int head,rear;
void In(char a,int x,int y)
{
    que.s[rear]=a;
    que.s1[rear]=x;
    que.s2[rear]=y;
    rear++;
}
void Out(int *x,int *y)
{
    *x=que.s1[head];
    *y=que.s2[head];
    head++;
}

int isEmpty()
{
    if(head==rear)
      return 1;
    else
      return 0;
}         
int main()
{
   int w,h,i,j,x,y,count,b[25][25],p1,p2;
   char a[25][25],temp;
   scanf("%d%d",&w,&h);
   while(!(w==0&&h==0))
   {
        getchar();
        for(i=0;i<h;i++)
        {
          for(j=0;j<w;j++)
          {
            scanf("%c",&a[i][j]);
            b[i][j]=0;
            if(a[i][j]=='@')
            {
                x=i;
                y=j;
            }
         }
         getchar();
       }
       head=rear=0;
       count=1;
       In(a[x][y],x,y);
       while(!isEmpty())
       {
            Out(&p1,&p2);
            i=p1,j=p2-1;
            if(j>=0&&a[i][j]=='.'&&b[i][j]==0)
            {
                In(a[i][j],i,j);
                b[i][j]=1;
                count++;
            }
            i=p1,j=p2+1;
            if(j<w&&a[i][j]=='.'&&b[i][j]==0)
            {
                In(a[i][j],i,j);
                b[i][j]=1;
                count++;
            }
            i=p1-1,j=p2;
            if(i>=0&&a[i][j]=='.'&&b[i][j]==0)
            {
                In(a[i][j],i,j);
                b[i][j]=1;
                count++;
            }
            i=p1+1,j=p2;
            if(i<h&&a[i][j]=='.'&&b[i][j]==0)
            {
                In(a[i][j],i,j);
                b[i][j]=1;
                count++;
            }
      }
     printf("%d\n",count);
     scanf("%d%d",&w,&h);
    }
     return 0;
}


  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值