题目链接

题意:

给你一个5*5的迷宫,0代表通路,1代表墙,找到从迷宫左上角到达右下角的最短路径,并输出路径。

题解:

先进行一遍BFS,得到vis数组,表示到该位置最少需要多少时间,然后从(4,4)位置倒着查路径,
查到符合的就直接break,防止重复

AC代码:

#include<stdio.h>
#include<string.h>
#include<algorithm>
#include<iostream>
#include<queue>
#include<stack>
using namespace std;
typedef long long ll;
const int maxn=7;
struct node{
    int x,y;
    node(int i=0,int j=0){x=i,y=j;};
};
int mp[maxn][maxn];
int vis[maxn][maxn];
int dis[4][2]={1,0,-1,0,0,1,0,-1};
void bfs(){
    queue<node>dq;
    node now(0,0),nex;
    dq.push(now);
    vis[0][0]=1;
    while(!dq.empty()){
        now=dq.front();
        dq.pop();
        for(int i=0;i<4;i++){
            nex.x=now.x+dis[i][0];
            nex.y=now.y+dis[i][1];
            if(nex.x>=0&&nex.x<5&&nex.y>=0&&nex.y<5&&mp[nex.x][nex.y]==0&&vis[nex.x][nex.y]==0){
                dq.push(nex);
                vis[nex.x][nex.y]=vis[now.x][now.y]+1;
                if(nex.x==4&&nex.y==4)return;
            }
        }
    }
}
int main(){
    stack<node>ds;
    for(int i=0;i<5;i++)
        for(int j=0;j<5;j++)scanf("%d",&mp[i][j]);
    bfs();
    node nw(4,4),ne;

    int ans=vis[4][4];
    ds.push(nw);
    while(true){
        for(int i=0;i<5;i++){
            ne.x=nw.x+dis[i][0];
            ne.y=nw.y+dis[i][1];
            if(ne.x>=0&&ne.x<5&&ne.y>=0&&ne.y<5&&vis[ne.x][ne.y]==ans-1){
                nw=ne;
                ans=ans-1;
                ds.push(nw);
                break;
            }
        }
        if(nw.x==0&&nw.y==0)break;
    }
    while(!ds.empty()){
        nw=ds.top();
        ds.pop();
        printf("(%d, %d)\n",nw.x,nw.y);
    }
    return 0;
}