1 条题解

  • 0
    @ 2025-2-14 21:09:17

    C++ :

    #include <algorithm>
    #include <iostream>
    #include <cstdio>
    #include <cstring>
    #include <queue>
    using namespace std;
    
    const int N = 300 + 5;
    struct Coord
    {
        int x,y,c;
        friend bool operator <(const Coord &s1,const Coord &s2)
        {
            return s1.c>s2.c;
        }
    };
    int n, m, sx, sy, ex, ey, vis[N][N], dir[4][2] = {{-1, 0}, {1, 0}, {0, -1}, {0, 1}};
    char maze[N][N];
    
    int bfs(int x, int y)
    {
        priority_queue <Coord> q;
        Coord a, t;
        a.x = x; a.y = y; a.c = 0;
        q.push(a);
        vis[x][y] = 1;
    
        while (!q.empty())
        {
            a = q.top();
            q.pop();
    
            if(a.x == ex && a.y == ey)
                return a.c;
            for(int i = 0; i < 4; ++i)
            {
                t.x = a.x + dir[i][0];
                t.y = a.y + dir[i][1];
                if(t.x >= 0 && t.x < n && t.y >= 0 && t.y < m && !vis[t.x][t.y] && maze[t.x][t.y] != 'K')
                {
                    vis[t.x][t.y] = 1;
                    if(maze[t.x][t.y] == '#')
                        t.c = a.c + 2;
                    if(maze[t.x][t.y] == '.' ||maze[t.x][t.y] == 'T')
                        t.c = a.c + 1;
                    q.push(t);
                }
            }
        }
        return -1;
    }
    
    int main()
    {
        while (cin >> n >> m, m + n)
        {
            memset(vis, 0, sizeof(vis));
            for(int i = 0; i < n; ++i)
            {
                cin >> maze[i];
                for(int j = 0; j < m; ++j)
                {
                    if(maze[i][j] == 'S')
                    {
                        sx = i; sy = j;
                    }
                    if(maze[i][j] == 'T')
                    {
                        ex = i; ey = j;
                    }
                }
            }
            cout << bfs(sx, sy) << endl;
        }
        return 0;
    }
    
    
    • 1

    信息

    ID
    658
    时间
    1000ms
    内存
    128MiB
    难度
    (无)
    标签
    递交数
    0
    已通过
    0
    上传者