|
发表于 2023-9-24 20:34:28
|
显示全部楼层
这段代码中的死循环问题是因为在判断边界时使用了分号,导致后面的语句一直执行。应该使用大括号将语句块括起来。
另外,这段代码中的 dfs 函数只是简单的深度优先搜索,并没有使用任何剪枝技巧,因此效率较低。可以考虑使用 A* 算法等更高效的搜索算法来解决这个问题。
以下是修改后的代码:
- #include <iostream>
- #include <queue>
- #include <cstring>
- using namespace std;
- const int MAXN = 505;
- const int INF = 0x3f3f3f3f;
- int dx[] = {-1, 1, 0, 0};
- int dy[] = {0, 0, -1, 1};
- int map[MAXN][MAXN];
- int n, m, sx, sy, ex, ey, ans;
- int dis[MAXN][MAXN];
- struct Node {
- int x, y, f;
- bool operator<(const Node& other) const {
- return f > other.f;
- }
- };
- bool isValid(int x, int y) {
- return x >= 0 && x < n && y >= 0 && y < m;
- }
- void Astar() {
- priority_queue<Node> pq;
- memset(dis, INF, sizeof(dis));
- pq.push({sx, sy, 0});
- dis[sx][sy] = 0;
- while (!pq.empty()) {
- Node cur = pq.top();
- pq.pop();
- int x = cur.x, y = cur.y;
- if (x == ex && y == ey) {
- ans = dis[x][y];
- return;
- }
- if (dis[x][y] < cur.f) continue;
- for (int i = 0; i < 4; i++) {
- int nx = x + dx[ i], ny = y + dy[ i];
- if (!isValid(nx, ny)) continue;
- int nd = dis[x][y] + (map[nx][ny] != map[x][y]);
- if (nd < dis[nx][ny]) {
- dis[nx][ny] = nd;
- pq.push({nx, ny, nd + abs(nx - ex) + abs(ny - ey)});
- }
- }
- }
- }
- int main() {
- while (cin >> n >> m && n && m) {
- memset(map, 0, sizeof(map));
- for (int i = 0; i < n; i++) {
- for (int j = 0; j < m; j++) {
- char tmp;
- cin >> tmp;
- if (tmp == '@') {
- map[ i][j] = 1;
- }
- }
- }
- cin >> sx >> sy >> ex >> ey;
- ans = INF;
- Astar();
- cout << ans << endl;
- }
- return 0;
- }
复制代码 |
|