正经题解|仙岛求药
2024-03-22 11:12:45
发布于:浙江
231阅读
0回复
0点赞
【算法分析】
求最少需要多少步,考虑使用广搜。从起点开始进行搜索,当搜索到终点时就结束。
【参考代码】
#include <bits/stdc++.h>
using namespace std;
char MAP[2009][2009];
bool vis[2009][2009];
int dir[4][2] = { -1,0,0,1,1,0,0,-1 };
struct node {
    int x, y, step;
}l,r;
int main() {
    int n, m;
    cin >> n >> m;
    int sx, sy, ex, ey;
    for (int i = 1; i <= n; i++) {
        cin >> MAP[i] + 1;
        for (int j = 1; j <= m; j++) {
            if (MAP[i][j] == '@') {
                sx = i, sy = j;
            }
            else if (MAP[i][j] == '*') {
                ex = i, ey = j;
            }
        }
    }
    queue<node> q;
    q.push({ sx,sy,0 });
    vis[sx][sy] = 1;
    while (q.size()) {
        r = q.front();
        q.pop();
        if (r.x == ex && r.y == ey) {
            cout << r.step;
            return 0;
        }
        for (int i = 0; i < 4; i++) {
            l.x = r.x + dir[i][0];
            l.y = r.y + dir[i][1];
            l.step = r.step + 1;
            if (l.x >= 1 && l.x <= n && l.y >= 1 && l.y <= m && !vis[l.x][l.y] && MAP[l.x][l.y] != '#') {
                vis[l.x][l.y] = 1;
                q.push(l);
            }
        }
    }
    cout << -1;
    return 0;
}
【时间复杂度】
【预计得分】
这里空空如也



有帮助,赞一个