53分求助(玄关)
查看原帖
53分求助(玄关)
772815
一咕咕一楼主2024/7/25 12:20
#include <bits/stdc++.h>
using namespace std;
int n, m;
int Sx, Sy, Tx, Ty;
const int M = 1000 + 7;
int vis[M][M];
char k[M][M];
class Node
{
public:
    int x, y, step;
};
int dx[4] = {-1, 1, 0, 0};
int dy[4] = {0, 0, -1, 1};
queue<Node> q;
void BFS()
{
    q.push({Sx, Sy, 0});
    vis[Sx][Sy] = 1;
    while (!q.empty())
    {
        Node top = q.front();
        q.pop();
        // cout << top.x << ' ' << top.y << ' ' << top.step << '\n';
        if (top.x == Tx && top.y == Ty)
        {
            cout << top.step;
            return;
        }
        if (k[top.x][top.y] >= 'A' && k[top.x][top.y] <= 'Z')
        {
            for (int i = 1; i <= n; i++)
            {
                bool flag = false;
                for (int j = 1; j <= m; j++)
                {
                    if (k[i][j] == k[top.x][top.y] && i != top.x && j != top.y)
                    {
                        top.x = i;
                        top.y = j;
                        flag = true;
                        break;
                    }
                }
                if (flag)
                    break;
            }
        }
        for (int i = 0; i < 4; i++)
        {
            int tx = top.x + dx[i];
            int ty = top.y + dy[i];
            if (tx >= 1 && tx <= n && ty >= 1 && ty <= m && !vis[tx][ty])
            {
                q.push({tx, ty, top.step + 1});
                vis[tx][ty] = 1;
            }
        }
    }
}
void solve(void)
{
    cin >> n >> m;
    for (int i = 1; i <= n; i++)
    {
        for (int j = 1; j <= m; j++)
        {
            char c;
            cin >> c;
            if (c == '#')
                vis[i][j] = 1;
            else if (c == '=')
                Tx = i, Ty = j;
            else if (c == '@')
                Sx = i, Sy = j;
            else if (c >= 'A' && c <= 'Z')
                k[i][j] = c;
        }
    }
    BFS();
    return;
}
int main()
{
    // freopen(".in","r",stdin);
    // freopen(".out","w",stdout);
    ios::sync_with_stdio(0);
    cin.tie(0);
    cout.tie(0);
    solve();

    return 0;
}
2024/7/25 12:20
加载中...