hdu Problem-1242 最基础的BFS

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

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

#include <iostream>
#include <cstdio>
#include <cstring>
#include <algorithm>
#include <queue>
using namespace std;
#define maxn 210
char 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;
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值