迷宫问题

这道题找最短路比不是很难, 难的是打印出最短路径所经过的节点,需要倒着进行一次bfs,这样才能根据保存在pre数组进行遍历,否则就会从终点到起点打印路径

#include <iostream>
using namespace std;
bool vis[1010][1010];
int mp[1010][1010];
typedef pair<int, int> PII;
const int N = 1e6 + 10;
//int dis[1010][1010];
PII pre[1010][1010];
int fx[] = {0, 0, 1, -1}, fy[] = {1, -1, 0, 0};
int n;

void bfs()
{
    PII qq[N];
    int hh = 0, tt = -1;
    qq[++tt] = {n - 1, n - 1};
    vis[n - 1][n - 1] = 1;
    while(hh <= tt)
    {
        PII t = qq[hh++];
        
        if(t.first == 0 && t.second == 0)
        break;
        
        for(int i = 0; i < 4; i++)
        {
            int x = fx[i] + t.first, y = fy[i] + t.second;
            if(x >= 0 && y >= 0 && x < n && y < n && !vis[x][y] && !mp[x][y])
            {
                vis[x][y] = 1;
                qq[++tt] = {x, y};
                pre[x][y] = t;
            }
        }
    }
}

int main()
{
    
    cin >> n;
    ios::sync_with_stdio(0);
    cin.tie(0);
    for(int i = 0; i < n; i++)
    for(int j = 0; j < n; j++)
    cin >> mp[i][j];
    bfs();
    int x, y;
    printf("0 0\n");
    PII end = {0, 0};
    while(end.first != n - 1 || end.second != n - 1)
    {
        printf("%d %d\n", pre[end.first][end.second].first, pre[end.first][end.second].second);
        x = end.first, y = end.second;
        end.first = pre[x][y].first, end.second = pre[x][y].second;
    }
    return 0;
}
posted @ 2022-05-04 20:09  Flying_bullet  阅读(45)  评论(0)    收藏  举报