90分求调
查看原帖
90分求调
846303
Stdinout楼主2024/12/6 23:16
#include <bits/stdc++.h>
#define FASTIO ios::sync_with_stdio(false);cin.tie(0);cout.tie(0);
using namespace std;
using ll = long long;
using pii = pair<int, int>;
const int dx[] = {0, 0, 1, -1};
const int dy[] = {1, -1, 0, 0};
const int N = 55;
char mp[N][N];
bool vis[N][N];
int minti[N][N], dist[N][N], n, m;
void bfs1(int x, int y) {
    queue<pii> q;
    q.push({x, y});
    vis[x][y] = true;
    minti[x][y] = 0;
    while (!q.empty()) {
        int x = q.front().first, y = q.front().second;
        q.pop();
        for (int i = 0; i < 4; i++) {
            int nx = x + dx[i], ny = y + dy[i];
            if (nx <= 0 || nx > n || ny <= 0 || ny > m) continue;
            if ((mp[nx][ny] >= 'A' && mp[nx][ny] <= 'Z') || vis[nx][ny]) continue;
            vis[nx][ny] = true;
            minti[nx][ny] = min(minti[x][y] + 1, minti[nx][ny]);
            q.push({nx, ny});
        }
    }
}
void bfs2(int x, int y) {
    queue<pii> q;
    q.push({x, y});
    dist[x][y] = 0;
    vis[x][y] = 1;
    while (!q.empty()) {
        int x = q.front().first, y = q.front().second;
        q.pop();
        for (int i = 0; i < 4; i++) {
            int nx = x + dx[i], ny = y + dy[i];
            if (nx <= 0 || nx > n || ny <= 0 || ny > m) continue;
            if (mp[nx][ny] == 'X') continue;
            if (vis[nx][ny]) continue;
            if (minti[nx][ny] < dist[x][y]) continue;
            if (mp[nx][ny] == 'D') {
                cout << dist[x][y] + 1 << '\n';
                exit(0);
            }
            dist[nx][ny] = dist[x][y] + 1;
            vis[nx][ny] = 1;  
            q.push({nx, ny});
        }
    }
}
int main() {
    FASTIO;
    cin >> n >> m;
    for (int i = 1; i <= n; ++i) {
        for (int j = 1; j <= m; ++j) {
            cin >> mp[i][j];
            dist[i][j] = -1;
        }
    } 
    memset(minti, 0x3f, sizeof minti);
    for (int i = 1; i <= n; ++i) {
        for (int j = 1; j <= m; ++j) {
            if (mp[i][j] == '*') {
                memset(vis, 0, sizeof vis);
                bfs1(i, j);
            }
        }
    }
    memset(vis, 0, sizeof vis);
    for (int i = 1; i <= n; ++i) {
        for (int j = 1; j <= m; ++j) {
            if (mp[i][j] == 'S') {
                bfs2(i, j);
            }
        }
    }
    cout << "KAKTUS\n";
    return 0;
}
2024/12/6 23:16
加载中...