LightOJ 1238 Power Puff Girls(BFS)

题解;

对a,b,c三个点各求一次bfs然后取最大值即可

代码

#include <cstdio>
#include <queue>
#include <cstring>
#include <iostream>
#include <cstdlib>
#include <algorithm>
#include <vector>
#include <map>
#include <string>
#include <set>
#include <ctime>
#include <cmath>
#include <cctype>
using namespace std;
#define maxn 100000
#define LL long long
int cas=1,T;
int n,m;
char mapp[25][25];
int visit[25][25];
int dx[] = {0,0,1,-1};
int dy[] = {1,-1,0,0};
struct Node
{ 
   int x,y;
   int step;
};

bool check(int x,int y)
{
    if (x<0 || y<0 || x>=n || y>=m)
        return true;
    if (visit[x][y] || mapp[x][y]=='#' || mapp[x][y]=='m' )
        return true;
    return false;
}
int bfs(Node s)
{
   visit[s.x][s.y]=1;
   queue<Node> q;
   q.push(s);

   while (!q.empty())
   {
       Node t = q.front();
       q.pop();
       if (mapp[t.x][t.y]=='h')
           return t.step;
       for (int i = 0;i<4;i++)
       {
           Node temp;
           temp.x = t.x+dx[i];
           temp.y = t.y+dy[i];
           if (check(temp.x,temp.y))
               continue;
           visit[temp.x][temp.y]=1;
           temp.step = t.step+1;
           q.push(temp);
       }
   }
   //memset(visit,0,sizeof(visit));
}
int main()
{
    scanf("%d",&T);
    while (T--)
    {
        printf("Case %d: ",cas++);
        Node a,b,c;
        scanf("%d%d",&n,&m);
        for (int i = 0;i<n;i++)
            scanf("%s",&mapp[i]);
        int atime,btime,ctime;
        for (int i = 0;i<n;i++)
            for (int j = 0;j<m;j++)
            {
               if (mapp[i][j]=='a')
               {
                   a.x=i;
                   a.y=j;
                   a.step=0;
                   atime = bfs(a);
                   memset(visit,0,sizeof(visit));
               }
               if (mapp[i][j]=='b')
               {
                   b.x=i;
                   b.y=j;
                   b.step=0;
                   btime = bfs(b);
                   memset(visit,0,sizeof(visit));
               }
               if (mapp[i][j]=='c')
               {
                   c.x=i;
                   c.y=j;
                   c.step=0;
                   ctime = bfs(c);
                   memset(visit,0,sizeof(visit));
               }
            }
        int mins =0;
        mins = max(atime,max(btime,ctime));
        printf("%d\n",mins);
        memset(mapp,0,sizeof(mapp));
        memset(visit,0,sizeof(visit));
    }
    //freopen("in","r",stdin);
    //scanf("%d",&T);
    //printf("time=%.3lf",(double)clock()/CLOCKS_PER_SEC);
    return 0;
}

你可能感兴趣的:(LightOJ 1238 Power Puff Girls(BFS))