2009-04-25 07:17:45來源不明

ACM 11352 11352 - Crazy King

作法:BFS

/***********************************/

#include<stdio.h>
#include<stdlib.h>
#include<string.h>
main()
{
 int n,a,b,c,d;
 char xx[102];
 scanf("%d",&n);
   {
    while(n--)
     {
      int x,y;
      int map[105][105]={0};
      int queue[10001][2],mmm[10001][2],mm=0;
      scanf("%d %d",&x,&y);
      for(a=0;a<x+3;a++)
       for(b=0;b<y+3;b++)
        map[a][b]=-1;
      for(a=2;a<x+2;a++)
       {
        scanf("%s",xx);
         for(b=0;b<y;b++)
          {
           c=b+2;
           if(xx[b]=='Z') { map[a][c]=-1; mmm[mm][0]=a;mmm[mm][1]=c;mm++;}
           if(xx[b]=='A') {map[a][c]=1;queue[0][0]=a;queue[0][1]=c;}
           if(xx[b]=='B') {map[a][c]=-2;}
           if(xx[b]=='.')  map[a][c]=0;
          }
       }
      for(d=0;d<mm;d++)
       {
        int a=mmm[d][0],c=mmm[d][1];
        if(map[a-1][c-2]==0) map[a-1][c-2]=-1;
        if(map[a-1][c+2]==0) map[a-1][c+2]=-1;
        if(map[a+1][c-2]==0) map[a+1][c-2]=-1;
        if(map[a+1][c+2]==0) map[a+1][c+2]=-1;
        if(map[a+2][c+1]==0) map[a+2][c+1]=-1;
        if(map[a+2][c-1]==0) map[a+2][c-1]=-1;
        if(map[a-2][c+1]==0) map[a-2][c+1]=-1;
        if(map[a-2][c-1]==0) map[a-2][c-1]=-1;
       }
       int top=0,ans=0,found=0;
       for(a=0;a<=top&&found==0;a++)
        {
         int mm=queue[a][0],nn=queue[a][1];
          for(b=-1;b<=1&&found==0;b++)
           for(c=-1;c<=1&&found==0;c++)
            {
             if(map[mm+b][nn+c]==-2) {ans=map[mm][nn];found=1;}
             if(map[mm+b][nn+c]==0)
              {
                map[mm+b][nn+c]=map[mm][nn]+1;
                top++;
                queue[top][0]=mm+b;queue[top][1]=nn+c; 
              }
            }
        }
       if(ans==0) printf("King Peter, you can't go now!\n");
       else printf("Minimal possible length of a trip is %d\n",ans); 
     }
   }
 return 0;
}