hdu 1175(广搜)

题意:容易理解...

思路:我开始的思路不好实现,而且有漏洞,时间复杂度也高,后来在网上学了下别人的方法,真心感觉很牛B,不仅代码好实现,而且时间复杂度比较低,具体看代码实现吧!!

代码实现:

#include<iostream>
#include<string.h>
#include<stdio.h>
#include<queue>
using namespace std;
struct node{
    int x;
    int y;
    int count;
};
int visited[1005][1005];
int b[4][2]={{-1,0},{1,0},{0,-1},{0,1}};
int map[1005][1005];
int n,m;
int sx,sy,ex,ey;
int ca(int x,int y)
{
    if(x>=1&&x<=n&&y>=1&&y<=m)
        return 1;
    else
        return 0;
}
int bfs()
{
    int i;
    queue<node>Q;
    struct node p,temp;
    p.x=sx;
    p.y=sy;
    p.count=0;
    visited[sx][sy]=-1;
    Q.push(p);
    while(!Q.empty())
    {
        p=Q.front();
        Q.pop();
        if(p.count>=3)
            return 0;
        if(p.x==ex&&p.y==ey)
            return 1;
        for(i=0;i<4;i++)
        {
            temp.x=p.x+b[i][0];
            temp.y=p.y+b[i][1];
            while(ca(temp.x,temp.y)&&map[temp.x][temp.y]==0)//把某个方向上的点全部搜完
            {
                if(visited[temp.x][temp.y]==0)//还没访问过的点进入队列
                {
                    visited[temp.x][temp.y]=-1;
                    temp.count=p.count+1;
                    if(temp.x==ex&&temp.y==ey)
                    {
                        if(temp.count<=3)
                            return 1;
                        else
                            return 0;
                    }
                    Q.push(temp);
                }
                temp.x=temp.x+b[i][0];
                temp.y=temp.y+b[i][1];
            }
        }
    }
    return 0;
}
int main()                                                                               
{
   int i,j,q,temp;
   while(scanf("%d%d",&n,&m)!=EOF&&(n+m)!=0)
   {
       for(i=1;i<=n;i++)
           for(j=1;j<=m;j++)
               scanf("%d",&map[i][j]);
       scanf("%d",&q);
       while(q--)
       {
           for(i=1;i<=n;i++)
              for(j=1;j<=m;j++)
                 visited[i][j]=0;
           scanf("%d%d%d%d",&sx,&sy,&ex,&ey);
           if(map[sx][sy]==map[ex][ey]&&map[sx][sy]!=0)
           {
               temp=map[ex][ey];
               map[ex][ey]=0;
               if(bfs())
                   printf("YES\n");
               else
                   printf("NO\n");
               map[ex][ey]=temp;
           }
           else
               printf("NO\n");  
       }
   }
   return 0;
}

 

posted on 2013-07-22 09:24  后端bug开发工程师  阅读(371)  评论(0编辑  收藏  举报

导航