H - find a friend (the direction-dependent bfs)

Description

X, as a big fan of outdoor sports, always do not want to stay at home. Now, he wants to pull out of the death house Y from home. Q. How much home from X to Y in the shortest time at home.
To simplify the problem, we map the abstract n matrix of m rows numbered 1 to n is from top to bottom, left to right column number 1 to m. Matrix 'X' represents the initial coordinates where X, 'Y' represents the position of the Y, '#' indicates the current position can not go, '*' indicates the current position can pass. Only adjacent each X 'to the left and right vertical ' movement, move every time takes 1 second.
Input

Multiple sets of input. Each test is first inputted two integers n, m (1 <= n , m <= 15) represents a size of the map. The next n lines of m characters. Ensure that the input data is valid.
Output

If X Y can be reached home, the minimum time the output, otherwise the output -1.
Sample

Input

March 3
X # Y


##
3 3
X#Y
#
#
#
Output

4
-1

#include<stdio.h>
#include<stdlib.h>
#include<string.h>
#include<malloc.h>
#include<queue>
using namespace std;
char Map[1100][1100];
int vis[1100][1100];
int tx[] = {0,1,0,-1};
int ty[] = {1,0,-1,0};
int n,m;
struct node
{
    int step;
    int x,y;
}t,k;
int flag;
void bfs(int x,int y)
{
    queue<node>q;
    vis[x][y] = 1;
    t.x = x;
    t.y = y;
    t.step = 0;
    q.push(t);
    while(!q.empty())
    {
        k = q.front();
        q.pop();
        if(Map[k.x][k.y] == 'Y')
        {
            printf("%d\n",k.step);
            return ;
        }
        for(int i=0;i<4;i++)
        {
            t.x = k.x+tx[i];
            t.y = k.y+ty[i];
            if(t.x>=0&&t.x<n&&t.y>=0&&t.y<m&&vis[t.x][t.y]==0&&Map[t.x][t.y]!='#')//如果这个是Map[t.x][t.y]=='*'就不行,因为X,Y没有算在内
            {
                t.step = k.step+1;
                vis[t.x][t.y] = 1;
                q.push(t);
            }
        }
    }
    printf("-1\n");
}
int main()
{
    int i,j;
    int x,y;
    while(~scanf("%d %d",&n,&m))
    {
        getchar();
        memset(vis,0,sizeof(vis));
        for(i=0;i<n;i++)
            scanf("%s",Map[i]);
        for(i=0; i<n; i++)
        {
            for(j=0; j<m; j++)
            {
                if(Map[i][j] == 'X')
                 {
                     x = i;
                     y = j;
                     break;
                 }
            }
//            if(j<m)
//                break;
        }
        bfs(x,y);
    }
    return 0;
}


Published 177 original articles · won praise 7 · views 30000 +

Guess you like

Origin blog.csdn.net/Fusheng_Yizhao/article/details/104887255