sdut oj 2779 找朋友

找朋友

Time Limit: 1000 ms Memory Limit: 65536 KiB

Submit Statistic

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

Hint

Source

zmx

bfs..

直接上bfs就可以没有什么坑。

#include <bits/stdc++.h>

using namespace std;

struct node{
    int x;
    int y;
    int n;
};
bool Map[20][20];
int v[4][2] = {{-1, 0}, {1, 0}, {0, -1}, {0, 1}};
int m, n, x, y, xx, yy;
void bfs();
int main(){
    ios::sync_with_stdio(0);
    char s;
    while(cin >> n >> m){
        memset(Map, 0, sizeof(Map));
        for(int i = 1; i <= n; i++){
            for(int j = 1; j <= m; j++){
                cin >> s;
                if(s == 'X'){
                    x = i;
                    y = j;
                    Map[i][j] = 1;
                }
                else if(s == '*')   Map[i][j] = 1;
                else if(s == '#')   Map[i][j] = 0;
                else{
                    xx = i;
                    yy = j;
                    Map[i][j] = 1;
                }
            }
        }
        bfs();
    }
    return 0;
}
void bfs(){
    queue <node> q;
    node p, r;
    Map[x][y] = 0;
    p.x = x;
    p.y = y;
    p.n = 0;
    q.push(p);
    while(!q.empty()){
        p = q.front();
        q.pop();
        if(p.x == xx && p.y == yy){
            cout << p.n << endl;
            return;
        }
        for(int i = 0; i < 4; i++){
            r.x = p.x + v[i][0];
            r.y = p.y + v[i][1];
            r.n = p.n + 1;
            if(r.x >= 1 && r.x <= n && r.y >= 1 && r.y <= m && Map[r.x][r.y]){
                Map[r.x][r.y] = 0;
                q.push(r);
            }
        }
    }
    cout << "-1" << endl;
}

猜你喜欢

转载自blog.csdn.net/zx__zh/article/details/82143481