FZU 2150 Fire Game(bfs)

#include <stdio.h>
#include <stdlib.h>
#include<queue>
#include<algorithm>
using namespace std;

struct Node
{
  int x,y;
  int rt;
};
Node node[200];
int n,m;
int cnt,gcnt,ans,ok,temp;
char mat[12][12];
int  vis[12][12];
int dir[4][2]={1,0,-1,0,0,1,0,-1};
bool fit(Node a)
{
  if(a.x<0||a.x>=n||a.y<0||a.y>=m||vis[a.x][a.y]==1) return false;
  if(mat[a.x][a.y]=='.') return false;
  return true;
}
void bfs(int s1,int s2)
{
  queue<Node> q;
  Node now,next;
  now.x=node[s1].x;
  now.y=node[s1].y;
  now.rt=0;
  vis[now.x][now.y]=1;
  q.push(now);
  now.x=node[s2].x;
  now.y=node[s2].y;
  now.rt=0;
  vis[now.x][now.y]=1;
  q.push(now);
  while(!q.empty())
  {
    now=q.front();
    q.pop();

    for(int i=0;i<4;i++)
    {
      next.x=now.x+dir[i][0];
      next.y=now.y+dir[i][1];
      if(fit(next))
      {
        //printf("%d %d
",next.x,next.y);
        next.rt=now.rt+1;
        vis[next.x][next.y]=1;
        if(temp<next.rt) temp=next.rt;
        q.push(next);
      }
    }
  }
}
int main()
{
    int t;
    int i,j,k,l;
    int cas=1;
    scanf("%d",&t);
    while(t--)
    {
      scanf("%d%d",&n,&m);
      gcnt=0;
      ans=100000;
      ok=0;
      for(i=0;i<n;i++)
      {
        scanf("%s",mat[i]);
        for(j=0;j<m;j++)
        {
          if(mat[i][j]=='#')
          {
            node[gcnt].x=i;
            node[gcnt++].y=j;
          }
        }
      }
     // printf("%d
",gcnt);
      for(i=0;i<gcnt;i++)
      {
        for(j=i;j<gcnt;j++)
        {
          temp=0;
          memset(vis,0,sizeof(vis));
          bfs(i,j);
          if(temp<ans)
          {
            int flag=0;
            for(k=0;k<n;k++)
            {
              for(l=0;l<m;l++)
              {
                if(vis[k][l]==1)
                  flag++;
              }
            }
            //printf("%d %d
",flag,gcnt);
            if(flag==gcnt)
            {
              ans=temp;
              ok=1;
            }
          }
        }
      }
      if(ok==0) ans=-1;
      if(gcnt==2) ans=0;
      printf("Case %d: %d
",cas++,ans);
    }
    return 0;
}

  

原文地址:https://www.cnblogs.com/sola1994/p/4354269.html