博客
关于我
每日一题-bfs最短路径变式
阅读量:320 次
发布时间:2019-03-04

本文共 2182 字,大约阅读时间需要 7 分钟。

为了解决这个问题,我们需要找到从迷宫入口到算法书遗落位置的最短路径,同时避免经过无法进入的房间、墨菲斯托的房间和莉莉丝的房间。我们可以使用广度优先搜索(BFS)来解决这个问题,并考虑两种情况:路径中不经过任何F或M房间,或者必须经过一个F或M房间。

方法思路

  • 情况一:计算从入口(1,1)到目标位置(r,c)的最短路径,且路径中不经过任何F或M房间。
  • 情况二:计算从入口(1,1)到每个F房间的最短路径,然后从每个F房间到目标位置的最短路径,取最小值。
  • 情况三:计算从入口(1,1)到每个M房间的最短路径,然后从每个M房间到目标位置的最短路径,取最小值。
  • 最后,比较这三种情况的最小值,返回最小值;如果无法找到路径,返回"IMPOSSIBLE"。

    解决代码

    #include 
    using namespace std;const int INF = 1e9;const int maxn = 1000 + 5;char g[maxn][maxn];int dx[] = {0, 1, 0, -1};int dy[] = {1, 0, -1, 0};int bfs(int x0, int y0, int x1, int y1, char forbidden) { if (x0 == x1 && y0 == y1) return 0; vector
    > dist(maxn, vector
    (maxn, INF)); dist[x0][y0] = 0; queue
    > q; q.push({x0, y0}); while (!q.empty()) { auto [x, y] = q.front(); q.pop(); for (int i = 0; i < 4; ++i) { int nx = x + dx[i]; int ny = y + dy[i]; if (nx < 1 || nx > maxn || ny < 1 || ny > maxn) continue; if (g[nx][ny] == forbidden) continue; if (dist[nx][ny] == INF) { dist[nx][ny] = dist[x][y] + 1; q.push({nx, ny}); if (nx == x1 && ny == y1) { return dist[nx][ny]; } } } } return dist[x1][y1];}int main() { int t; cin >> t; for (int _t = 0; _t < t; ++_t) { int n, m, r, c; cin >> n >> m >> r >> c; g = {{0}}; for (int i = 1; i <= n; ++i) { string s; cin >> s; for (int j = 1; j <= m; ++j) { g[i][j] = s[j-1]; } } int ans1 = bfs(1, 1, r, c, 'F'); int ans2 = INF; for (int x = 1; x <= n; ++x) { for (int y = 1; y <= m; ++y) { if (g[x][y] == 'F') { int d1 = bfs(1, 1, x, y, 'M'); int d2 = bfs(x, y, r, c, 'F'); if (d1 != INF && d2 != INF) { int total = d1 + d2; if (total < ans2) { ans2 = total; } } } } } int ans3 = INF; for (int x = 1; x <= n; ++x) { for (int y = 1; y <= m; ++y) { if (g[x][y] == 'M') { int d1 = bfs(1, 1, x, y, 'F'); int d2 = bfs(x, y, r, c, 'F'); if (d1 != INF && d2 != INF) { int total = d1 + d2; if (total < ans3) { ans3 = total; } } } } } int ans = min(ans1, ans2, ans3); if (ans == INF) { cout << "IMPOSSIBLE" << endl; } else { cout << ans << endl; } }}

    代码解释

  • BFS函数:用于计算从起点到终点的最短路径,避开特定类型的房间。
  • 主函数:读取输入数据,调用BFS函数计算三种情况的最短路径,并输出结果。
  • 情况一:计算不经过F或M房间的最短路径。
  • 情况二:计算经过F房间的最短路径。
  • 情况三:计算经过M房间的最短路径。
  • 结果判断:比较三种情况的结果,输出最小值或"IMPOSSIBLE"。
  • 转载地址:http://unrq.baihongyu.com/

    你可能感兴趣的文章
    Nodejs express 获取url参数,post参数的三种方式
    查看>>
    nodejs http小爬虫
    查看>>
    nodejs libararies
    查看>>
    nodejs npm常用命令
    查看>>
    nodejs npm常用命令
    查看>>
    Nodejs process.nextTick() 使用详解
    查看>>
    NodeJS yarn 或 npm如何切换淘宝或国外镜像源
    查看>>
    nodejs 中间件理解
    查看>>
    nodejs 创建HTTP服务器详解
    查看>>
    nodejs 发起 GET 请求示例和 POST 请求示例
    查看>>
    NodeJS 导入导出模块的方法( 代码演示 )
    查看>>
    nodejs 开发websocket 笔记
    查看>>
    nodejs 的 Buffer 详解
    查看>>
    NodeJS 的环境变量: 开发环境vs生产环境
    查看>>
    nodejs 读取xlsx文件内容
    查看>>
    nodejs 运行CMD命令
    查看>>
    Nodejs+Express+Mysql实现简单用户管理增删改查
    查看>>
    nodejs+nginx获取真实ip
    查看>>
    nodejs-mime类型
    查看>>
    NodeJs——(11)控制权转移next
    查看>>