hdu Problem-1242 最基础的BFS

来源:互联网 发布:mac卸载qq 编辑:程序博客网 时间:2024/06/05 17:01

这道题的题意大概就是公主被困在监狱里,然后她的朋友去救她,‘.’表示道路,‘a’表示公主所在位置,‘r’表示朋友所在位置,求r到a的最短距离。

这题我的思路是用BFS,直接用stl的queue来做,具体在代码后都有注释。

#include <iostream>#include <cstdio>#include <cstring>#include <algorithm>#include <queue>using namespace std;#define maxn 210char str[maxn][maxn];int vis[maxn][maxn];int dx[] = { 0,0,1,-1 };//x的方向int dy[] = { 1,-1,0,0 };//y的方向struct node {    int x, y;    int step;};//x,y记录点的坐标,step记录所走的距离;int main() {    int n,m;    int ax, by;    while (~scanf("%d%d%*c", &n, &m)) {//%*c跳过一个字符(回车)        queue<node>q;        for (int i = 0; i < n; i++) {            for (int j = 0; j < m; j++) {                scanf("%c", &str[i][j]);                if (str[i][j] == 'r') {                    ax = i;                    by = j;                }//找到并记录公主的朋友的位置;            }            getchar();        }        memset(vis, 0, sizeof(vis));        node e, s;        int flag = 1;        s.step = 0;        s.x = ax;        s.y = by;        q.push(s);        vis[s.x][s.y] = 1;        while (!q.empty()) {//BFS实现广搜            s = q.front();            q.pop();            if (str[s.x][s.y] == 'a') {                printf("%d\n", s.step);                flag = 0;                break;            }            for (int k = 0; k < 4; k++) {                e.x = s.x + dx[k];                e.y = s.y + dy[k];                if (e.x< 0 || e.x >= n || e.y < 0 || e.y >= m || vis[e.x][e.y]||str[e.x][e.y] =='#')                    continue;                if (str[e.x][e.y] == 'x')                    e.step = s.step + 2;                else                    e.step = s.step + 1;                q.push(e);                vis[e.x][e.y] = 1;            }        }        if(flag)            printf("Poor ANGEL has to stay in the prison all his life.\n");    }    return 0;}
0 0
原创粉丝点击