迷宫脱困难题:二分查找结合 BFS 寻最小参数 k
这是一个典型的带有参数调整的最短路径问题,需要找到满足特定条件的参数k。我们可以使用二分查找结合BFS来解决这个问题。 ```cpp #include <iostream> #include <vector> #include <queue> #include <iomanip> #include <cmath> using namespace std; const double EPS = 1e-8; const int INF = 1e9; struct State { int x, y; double time; State(int x, int y, double time) : x(x), y(y), time(time) {} }; int n, m; int sx, sy, tx, ty; vector<vector<int>> maze; double s; bool is_valid(int x, int y) { return x >= 0 && x < n && y >= 0 && y < m && maze[x][y] == 0; } bool check(double k) { vector<vector<double>> dist(n, vector<double>(m, INF)); dist[sx][sy] = 0.0; queue<State> q; q.push(State(sx, sy, 0.0)); int dx[] = {-1, 1, 0, 0}; int dy[] = {0, 0, -1, 1}; while (!q.empty()) { State curr = q.front(); q.pop(); if (abs(curr.time - dist[curr.x][curr.y]) > EPS) continue; for (int i = 0; i < 4; ++i) { int nx = curr.x + dx[i]; int ny = curr.y + dy[i]; if (!is_valid(nx, ny)) continue; double new_time = curr.time; if (i < 2) { // up or down new_time += k; } else { // left or right new_time += 1.0; } if (new_time < dist[nx][ny] - EPS) { dist[nx][ny] = new_time; q.push(State(nx, ny, new_time)); } } } return abs(dist[tx][ty] - s) < EPS; } int main() { cin >> n >> m; cin >> sx >> sy >> tx >> ty; sx--; sy--; tx--; ty--; // convert to 0-based index maze.resize(n, vector<int>(m)); for (int i = 0; i < n; ++i) { for (int j = 0; j < m; ++j) { cin >> maze[i][j]; } } cin >> s; double left = 0.0, right = 1e6; double ans = 0.0; while (right - left > EPS) { double mid = (left + right) / 2; if (check(mid)) { ans = mid; right = mid; } else { left = mid; } } cout << fixed << setprecision(3) << ans << endl; return 0; } ``` 1. 二分查找的精度控制很重要,EPS设置为1e-8可以保证足够的精度。 2. BFS实现时需要注意处理浮点数比较的精度问题,使用EPS进行比较。 3. 移动方向的代价计算需要区分上下移动和左右移动,上下移动消耗k秒,左右移动消耗1秒。 ######[AI写代码神器 | 735点数解答 | 2025-07-01 15:27:29]
- 易语言:实现搜索通配符功能,解决搜索内容超255问题(字节豆包 | 32点数解答 | 2026-02-09 16:44:31)45
- 代码优化:“A_寻找通配符”子程序的改进之路(字节豆包 | 1248点数解答 | 2026-02-09 16:45:52)48
- 易语言:A_寻找通配符子程序完整实现及详细代码解读(字节豆包 | 1368点数解答 | 2026-02-09 16:49:12)40
- 迷宫探秘:求解扶苏走出数字矩阵迷宫所需步数及循环判定(字节豆包 | 819点数解答 | 2025-11-26 19:27:35)72
- 易语言代码优化:自动出售物资子程序整合与优化全解析(DeepSeek | 2181点数解答 | 2025-07-23 10:26:29)214
- 大文件多线程上传流程全解析:从步骤说明到代码示例及注意事项(字节豆包 | 1079点数解答 | 2025-09-24 13:45:27)113
- 易语言:实现 Api 读取整数型内存数据的代码剖析(字节豆包 | 34点数解答 | 2026-02-09 11:48:57)24
- 旅行售货员问题:详细步骤剖析与贪心算法Python代码实现(字节豆包 | 444点数解答 | 2024-12-17 03:32:59)275
- Dev C++ 实现旅行售货员问题:最小路程路线代码与详细解析 (字节豆包 | 448点数解答 | 2024-12-17 03:33:42)176
- C++ 求解 P1020 小核桃与删除字符串问题:双指针与枚举策略 (字节豆包 | 330点数解答 | 2026-02-07 18:40:10)23
- Linux开发:用find命令查找/usr目录下超1MB的文件(百度文心 | 153点数解答 | 2023-11-09 18:45:10)206
- 8 个实用命令,助 Linux 开发者轻松查找服务器平均负载!(百度文心 | 311点数解答 | 2023-11-09 18:47:10)223