11352 - Crazy King

#include<stdio.h>
#include<string.h>
#include<algorithm>
#include<queue>
using namespace std;
char mat[101][101];
int color[101][101];
int cost[200][200];
int main()
{
    char str[101][101];
    int t,R,C,a,b,c,d,x,i,j;
    int X[8]= {1,1,0,-1,-1,-1,0,1};
    int Y[8]= {0,1,1,1,0,-1,-1,-1};
    int W[8]= {2,1,-1,-2,-2,-1,1,2};
    int Z[8]= {1,2,2,1,-1,-2,-2,-1};
    scanf("%d",&t);
    for(x=1; x<=t; x++)
    {
        scanf("%d%d",&R,&C);
        getchar();
        for(i=0; i<R; i++)
        {
            for(j=0; j<C; j++)
            {
                scanf("%c",&str[i][j]);
            }
            getchar();
        }
        for(i=0; i<R; i++)
        {
            for(j=0; j<C; j++)
            {
                if(str[i][j]=='A')
                {
                    a=i;
                    b=j;
                }
            }
        }
        int ux,uy,vx,vy,k,e=0;
        for(i=0; i<R; i++)
        {
            for(j=0; j<C; j++)
            {
                if(str[i][j]=='Z')
                {
                    for(k=0; k<8; k++)
                    {
                        vx=i+W[k];
                        vy=j+Z[k];
                        if((vx>=0&&vx<R)&&(vy>=0&&vy<C)&&(str[vx][vy]!='A'&&str[vx][vy]!='B'&&str[vx][vy]!='Z'))
                        {
                            str[vx][vy]='X';
                        }
                    }
                }
            }
        }
        queue<int>Q;
        Q.push(a);
        Q.push(b);
        color[a][b]=1;
        while(!Q.empty())
        {
            ux=Q.front();
            Q.pop();
            uy=Q.front();
            Q.pop();
            for(k=0; k<8; k++)
            {
                vx=ux+X[k];
                vy=uy+Y[k];
                if((vx>=0&&vx<R)&&(vy>=0&&vy<C)&&color[vx][vy]!=1&&str[vx][vy]!='Z'&&str[vx][vy]!='X')
                {
                    color[vx][vy]=1;
                    Q.push(vx);
                    Q.push(vy);
                    cost[vx][vy]=cost[ux][uy]+1;
                }
                if(str[vx][vy]=='B')
                {
                    for(i=0; i<R; i++)
                    {
                        for(j=0; j<C; j++)
                        {
                            if(str[i][j]=='B')
                            {
                                c=i;
                                d=j;
                                e++;
                                break;
                            }
                        }
                    }
                }
            }
        }
        if(e>0)
        {
            printf("Minimal possible length of a trip is %d\n",cost[c][d]);
        }
        else
        {
            printf("King Peter, you can't go now!\n");
        }
        memset(str,'\0',sizeof(str));
        memset(cost,0,sizeof(cost));
        memset(color,0,sizeof(color));
    }
    return 0;
}

0 comments: (+add yours?)