C++_BFS求最短路径

来源:互联网 发布:林书豪职业生涯数据 编辑:程序博客网 时间:2024/06/16 20:56

Description

Angel was caught by the MOLIGPY! He was put in prison by Moligpy. The prison is described as a N * M (N, M <= 200) matrix. There are WALLs, ROADs, and GUARDs in the prison.

Angel’s friends want to save Angel. Their task is: approach Angel. We assume that “approach Angel” is to get to the position where Angel stays. When there’s a guard in the grid, we must kill him (or her?) to move into the grid. We assume that we moving up, down, right, left takes us 1 unit time, and killing a guard takes 1 unit time, too. And we are strong enough to kill all the guards.

You have to calculate the minimal time to approach Angel. (We can move only UP, DOWN, LEFT and RIGHT, to the neighbor grid within bound, of course.)

Input

First line contains two integers stand for N and M.

Then N lines follows, every line has M characters. “.” stands for road, “a” stands for Angel, and “r” stands for each of Angel’s friend.

Process to the end of the file.

Output

For each test case, your program should output a single integer, standing for the minimal time needed. If such a number does no exist, you should output a line containing “Poor ANGEL has to stay in the prison all his life.”

Sample Output

13

1、Process to the end of the file.这句话坑了我好久,这句话的意思就是一直输入测试用例直到EOF
2、解题的时候仔细读题,这次就没看到变量的范围然后一开始一直在想动态分配。

Solution

#include <iostream>#include <queue>#include <cstring>using namespace std;struct node{    int x, y, d;    node(int x, int y, int d):x(x), y(y), d(d){};    bool operator < (const node b) const    {        return d > b.d;    }};const int dx[] = {1, -1, 0, 0};const int dy[] = {0, 0, 1, -1};int x_size, y_size;char mmap[205][205];char vis[205][205];int fx, fy;int dfs();int main(){    while(cin >> x_size >> y_size)    {        for(int i = 1;i<=x_size;i++)        {            for(int j = 1;j<=y_size;j++)            {                cin >> mmap[i][j];            }        }        int ans = dfs();        if(ans == -1) cout << "Poor ANGEL has to stay in the prison all his life." << endl;        else cout << ans << endl;    }    return 0;}int dfs(){    priority_queue<node> qmap;    memset(vis, 0, sizeof(vis));    for(int i = 1;i<=x_size;i++)        for(int j = 1;j<=y_size;j++)            if(mmap[i][j] == 'a')                qmap.push(node(i, j, 0));    while(!qmap.empty())    {        node u = qmap.top();        qmap.pop();        if(vis[u.x][u.y]) continue;        vis[u.x][u.y] = 1;        if(mmap[u.x][u.y] == 'r') return u.d;        for(int i = 0;i<4;i++)        {            node t(u.x+dx[i], u.y+dy[i], 0);            if(t.x <= 0 || t.x > x_size || t.y <=0 || t.y > y_size || mmap[t.x][t.y] == '#' || vis[t.x][t.y])                continue;            if(mmap[t.x][t.y] == 'x')                t.d = u.d+2;            else                t.d = u.d + 1;            qmap.push(t);        }    }    return -1;}
0 0