CDOJ 解救小Q

#include<stdio.h>
#include<string.h>
struct point
{
    int x,y;
};
struct point gate[26][2],que[2505];
char box[55][55];
int  vis[55][55],cost[55][55];
int dx[4]={-1,0,1,0};
int dy[4]={0,-1,0,1};
int n,m;
bool is_not(int x,int y)
{
    if(x<0 || y <0 || x >=n || y >=m || vis[x][y] || box[x][y]=='#')
        return true;
    else  return false;
}
int bfs(int lx,int ly)
{
    int rear=0,fron=0,i;
    que[rear].x=lx;
    que[rear].y=ly;
    rear++;
    while(fron<rear)
    {
        for(i=0;i<4;i++)
        {
            int nx=que[fron].x+dx[i];
            int ny=que[fron].y+dy[i];
            if(is_not(nx,ny))  continue;
            vis[nx][ny]=1;
            int  tmpx=nx,tmpy=ny;
            if(box[nx][ny]>='a' && box[nx][ny]<='z')//遇到传送阵的情况,改变下一层xy的值
                {
                        if(gate[box[nx][ny]-'a'][0].x==nx && gate[box[nx][ny]-'a'][0].y==ny)
                        {
                            tmpx=gate[box[nx][ny]-'a'][1].x;
                            tmpy=gate[box[nx][ny]-'a'][1].y;
                        }
                       else{
                            tmpx=gate[box[nx][ny]-'a'][0].x;
                            tmpy=gate[box[nx][ny]-'a'][0].y;
                           }
                }
            nx=tmpx;
            ny=tmpy;
            cost[nx][ny]=cost[que[fron].x][que[fron].y]+1;
            que[rear].x=nx;
            que[rear].y=ny;
            rear++;
            if(box[nx][ny]=='Q')  return  cost[nx][ny];
        }
        fron++;
    }
   return 0;
}
int main()
{  int T;
   scanf("%d",&T);
   while(T--)
   {
    int i,j,L_x,L_y;
    scanf("%d%d",&n,&m);
    getchar();
    memset(cost,0,sizeof(cost));
    memset(vis,0,sizeof(vis));
    memset(gate,-1,sizeof(gate));
    for(i=0;i<n;i++)
    {
        for(j=0;j<m;j++)
        {   char  ch;
         scanf("%c",&ch);
         box[i][j]=ch;
         if(ch=='L')
         {
             box[i][j]='#';
             L_x=i;
             L_y=j;
             vis[i][j]=1;
         }
        else  if(ch>='a'&&ch<='z')
        {
            if(gate[ch-'a'][0].x==-1)
            {
                gate[ch-'a'][0].x=i;
                gate[ch-'a'][0].y=j;
            }
            else
            {
                gate[ch-'a'][1].x=i;
                gate[ch-'a'][1].y=j;
            }
        }
       }
     getchar();
    }
     int ans=bfs(L_x,L_y);
     if(ans==0)  printf("-1\n");
     else printf("%d\n",ans);
   }
    return 0;
}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值