hdu2531 (BFS)

hdu 2531 Catch him

块的BFS,以块中一点做搜索,其余点用相对该点的偏移值表示即可

#include <iostream>
#include <cstdio>
#include <cstring>
#include <cstring>
#include <vector>
#include <queue>
#define N 105
using namespace std;
int dx[4]={0,1,0,-1};
int dy[4]={1,0,-1,0};
int px[N],py[N];    //偏移值
bool vis[N][N];
char maze[N][N];
int ans,pn,h,w;

typedef struct node{
    int x,y;
    int dis;
}Node;
queue<Node> q;
bool ok(int xx,int yy)
 {
     int i,x,y;
     for (i=1;i<=pn;i++)
     {
         x=xx+px[i]; y=yy+py[i];
         if (x<1 || x>h || y<1 || y>w || maze[x][y]=='O')
             return false;
     }
     return true;
 }
 int kill(int x,int y)
 {
     int i;
     for (i=1;i<=pn;i++)
         if (maze[x+px[i]][y+py[i]]=='Q') return 1;
     return 0;
 }
int bfs(int x,int y){
    vis[x][y] = 1;
   while(!q.empty()) q.pop();
   Node u = {x,y,0};
   Node v;
   q.push(u);
   int sx,sy,sdis;
   while(!q.empty()){
        u = q.front();q.pop();
        for(int j = 0;j < 4;j ++){
            sx = u.x + dx[j];
            sy = u.y + dy[j];
            sdis = u.dis + 1;
            if(!ok(sx,sy) || vis[sx][sy]) continue;
            vis[sx][sy] = 1;
            if(kill(sx,sy)){
                //cout << "ok" << endl;
                return sdis;
            }
            v = {sx,sy,sdis};
            q.push(v);
        }
   }
   return -1;
}
int main()
{
    int flag,x,y,i,j;
    while(scanf("%d %d",&h,&w) && h){
        flag = 0;
        memset(vis,0,sizeof(vis));
        memset(maze,0,sizeof(maze));
        pn = 0;
        for (i=1;i<=h;i++) scanf("%s",maze[i]+1);
        for (i=1;i<=h;i++)
            for (j=1;j<=w;j++)
             if (maze[i][j]=='D')
             {
                 if (!flag)
                 {
                     flag=1;
                     x=i; y=j;
                 }
                 pn++;
                 px[pn]=i-x; py[pn]=j-y;
            }
        ans = bfs(x,y);
        if(ans == -1)
            printf("Impossible\n");
        else
            printf("%d\n",ans);
    }
    return 0;
}

 

posted on 2016-07-10 15:16  Tob's_the_top  阅读(108)  评论(0编辑  收藏  举报

导航