找朋友

来源:互联网 发布:淘宝客服服务助手 编辑:程序博客网 时间:2024/04/29 03:02
找朋友
Time Limit:1000MS     Memory Limit:65536KB     64bit IO Format:%lld & %llu
Submit Status

Description

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

Input

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

Output

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

Sample Input

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

Sample Output

4-1
这道题,可以用BFS做,也可以用DFS做,之前写过一片DFS的博客,所以这次就用了BFS
BFS的基本思想大致就是从X开始,按照一定的移动顺序查找能够继续往下走的路,进入队列,相应的步数加1,同时,标记这条路已经走过,最后首先到达Y的步数肯定就是最小的。
#include <iostream>#include <algorithm>#include <stdio.h>#include <string.h>#include <stdlib.h>using namespace std;char sz[16][16];int vis[16][16];struct node{    int i;//记录行坐标和列坐标    int j;    int step;//记录步数} dl[10000];//开一个足够大的队列int fx[] = {0,0,-1,1};//行走规则int fy[] = {-1,1,0,0};int n,m;void BFS(int bi,int bj){    int a,z;    struct node head,next;//生命两个node型变量    head.i = bi;//初始化    head.j = bj;    head.step = 0;    vis[bi][bj] = 1;//对该点进行标记已经走过    a = z = 0;//a代表队列头,z代表队列尾    dl[z++] = head;    while(a < z)    {        head = dl[a++];        vis[head.i][head.j] = 1;        if(sz[head.i][head.j] == 'Y')//找到目标,输出步数        {            printf("%d\n",head.step);            return ;        }        int fo;        for(fo = 0; fo < 4; fo++)//按照行走规则将满足条件的数加进队列        {            next.i = head.i + fx[fo];            next.j = head.j + fy[fo];            next.step = head.step;            if(next.i >= 0 && next.i < n && next.j >= 0 && next.j < m &&  vis[next.i][next.j] == 0 && sz[next.i][next.j] != '#')            {                next.step = next.step + 1;                dl[z++] = next;            }        }    }    printf("-1\n");    return ;}int main(){    int x,y,bi,bj;    while(scanf("%d%d%*c",&n,&m)!= EOF)    {        memset(vis,0,sizeof(vis));        for(x = 0; x < n; x++)        {            scanf("%s",sz[x]);        }        for(x = 0; x < n; x++)        {            for(y = 0; y < m; y++)            {                if(sz[x][y] == 'X')                {                    bi = x;                    bj = y;                    break;                }            }        }        BFS(bi,bj);    }    return 0;}


0 0
原创粉丝点击