C++_BFS求最短路径

这篇博客讲述了如何使用BFS算法解决一个救援任务问题:在一个包含墙壁、道路和守卫的N×M矩阵监狱中,计算救出被囚禁的天使所需的最短时间。题目要求在遇到守卫时需要花费1单位时间将其击败,并且只能向上、下、左、右移动。博主分享了解题过程中的注意事项和解决方案。
摘要由CSDN通过智能技术生成

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.”

好的,以下是一个基于C++BFS最短路径的示例代码: ```cpp #include <iostream> #include <queue> #include <cstring> using namespace std; const int MAXN = 1005; // 最大节点数 const int INF = 0x3f3f3f3f; // 无穷大 int n, m; // n表示节点个数,m表示边数 int dis[MAXN]; // 存储起点到每个节点的距离 bool vis[MAXN]; // 记录每个节点是否被访问过 int head[MAXN], to[MAXN<<1], nxt[MAXN<<1], edge[MAXN<<1], cnt; // 邻接表存图 void addEdge(int u, int v, int w) { to[++cnt] = v; nxt[cnt] = head[u]; edge[cnt] = w; head[u] = cnt; } void bfs(int start) { memset(dis, INF, sizeof(dis)); // 初始化距离为无穷大 memset(vis, false, sizeof(vis)); // 初始化所有节点都未被访问过 dis[start] = 0; // 起点到自己的距离为0 vis[start] = true; // 起点已经访问过了 queue<int> q; // 定义一个队列,用于广度优先搜索 q.push(start); // 将起点加入队列 while (!q.empty()) { int u = q.front(); q.pop(); // 取出队首节点 for (int i = head[u]; i; i = nxt[i]) { int v = to[i], w = edge[i]; if (!vis[v]) { // 如果这个节点未被访问过 dis[v] = dis[u] + w; // 更新距离 vis[v] = true; // 标记为已访问 q.push(v); // 将其加入队列 } } } } int main() { cin >> n >> m; for (int i = 1; i <= m; ++i) { int u, v, w; cin >> u >> v >> w; addEdge(u, v, w); addEdge(v, u, w); // 无向图需要加两条边 } int start; cin >> start; bfs(start); for (int i = 1; i <= n; ++i) { if (dis[i] != INF) { cout << start << " 到 " << i << " 的最短距离为:" << dis[i] << endl; } } return 0; } ``` 这段代码使用邻接表存图,时间复杂度为O(n+m),其中n表示节点数,m表示边数。在实际使用中,可以根据自己的需进行修改。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值