找朋友(BFS)

版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/SDUTyangkun/article/details/88304012

找朋友

Time Limit: 1000 ms Memory Limit: 65536 KiB

Submit Statistic Discuss

Problem Description

X,作为户外运动的忠实爱好者,总是不想呆在家里。现在,他想把死宅Y从家里拉出来。问从X的家到Y的家的最短时间是多少。

为了简化问题,我们把地图抽象为n*m的矩阵,行编号从上到下为1 到 n,列编号从左到右为1 到 m。矩阵中’X’表示X所在的初始坐标,’Y’表示Y的位置 , ’#’表示当前位置不能走,’ * ’表示当前位置可以通行。X每次只能向上下左右的相邻的 ’*’ 移动,每移动一次耗时1秒。

Input

多组输入。每组测试数据首先输入两个整数n,m(1<= n ,m<=15 )表示地图大小。接下来的n 行,每行m个字符。保证输入数据合法。

Output

若X可以到达Y的家,输出最少时间,否则输出 -1。

Sample Input

3 3
X#Y
***
#*#
3 3
X#Y
*#*
#*#

Sample Output

4
-1
#include <iostream>
#include <cstdio>
#include <cstring>
#include <queue>
using namespace std;
char mp[20][20];
int vis[20][20];
int n,m;
int xx[4]={0,1,0,-1};
int yy[4]={1,0,-1,0};
struct node
{
    int x,y;
    int step;
};
int judge(int x, int y)
{
    if(x >= 0 && x < n && y >= 0 && y < m )
      return 1;
    else
        return 0;
}
void bfs(int x, int y)
{
    node u;
    u.step = 0;
    u.x = x;
    u.y = y;
    queue<node>q;
    q.push(u);
    vis[x][y] = 1;
    while(!q.empty())
    {
        node tmp = q.front();
        q.pop();
        if(mp[tmp.x][tmp.y] == 'Y')
        {
            printf("%d\n", tmp.step);
            return;
        }

        for(int i = 0; i < 4; i++)
        {
            int tx = tmp.x+xx[i];
            int ty = tmp.y+yy[i];
            if(judge(tx, ty)&&!vis[tx][ty]&&mp[tx][ty]!='#')
            {
                vis[tx][ty] = 1;
                node v;
                v.x = tx;
                v.y = ty;
                v.step = tmp.step+1;
                q.push(v);
            }
        }
    }

  printf("-1\n");
}
int main()
{
    while(~scanf("%d%d", &n,&m))
    {
        memset(mp, 0, sizeof(mp));
        memset(vis, 0, sizeof(vis));
        int x1, y1;

        for(int i=0; i < n; i++)
        {
            scanf("%s", mp[i]);
            for(int j = 0; j < m; j++)
            {
                if(mp[i][j] == 'X')
                {
                    x1 = i;
                    y1 = j;
                }
            }
        }
        bfs(x1,y1);
    }
    return 0;
}

猜你喜欢

转载自blog.csdn.net/SDUTyangkun/article/details/88304012
今日推荐