BFS 5pts 求助
查看原帖
BFS 5pts 求助
1028403
封禁用户楼主2024/5/24 21:08

rt,样例 和 Subtask #4 全过,其他有 AC 有 WA。

用 DFS 无果。

#include <iostream>
#include <queue>
#include <cstring>
using namespace std;
const int N = 5e3 + 10;
const int dx[] = {-1, 1, 0, 0};
const int dy[] = {0, 0, -1, 1};
int n, m, a, b, dp[N][N];
char c[N][N];
struct Node {
    int x, y;
};
queue<Node> q;
void init() {
    memset(dp, -1, sizeof dp);
    dp[a][b] = 0;
    q.push({a, b});
}
int bfs() {
    int ans = (c[a][b] == 'S' ? 1 : c[a][b] == 'M' ? 5 : 10);
    while (!q.empty()) {
        Node p = q.front();
        q.pop();
        for (int i = 0; i < 4; i++) {
            int kx = p.x + dx[i];
            int ky = p.y + dy[i];
            if (kx >= 1 && kx <= n && ky >= 1 && ky <= m && 
                dp[kx][ky] == -1 && c[kx][ky] != '*') {
                    dp[kx][ky] = dp[p.x][p.y] + 1;
                    q.push({kx, ky});
                    if (c[kx][ky] == 'S') ans++;
                    if (c[kx][ky] == 'M') ans += 5;
                    if (c[kx][ky] == 'L') ans += 10;
                }
        }
    }
    return ans;
}
int main()
{
    cin >> n >> m;
    for (int i = 1; i <= n; i++)
        for (int j = 1; j <= m; j++)
            cin >> c[i][j];
    cin >> a >> b;
    init();
    cout << bfs() << endl;
    return 0;
}
2024/5/24 21:08
加载中...