迷宫问题

Time Limit: 1000MS   Memory Limit: 65536K
Total Submissions: 9311   Accepted: 5514

Description

定义一个二维数组:

int maze[5][5] = {
0, 1, 0, 0, 0,
0, 1, 0, 1, 0,
0, 0, 0, 0, 0,
0, 1, 1, 1, 0,
0, 0, 0, 1, 0,
};

它表示一个迷宫,其中的1表示墙壁,0表示可以走的路,只能横着走或竖着走,不能斜着走,要求编程序找出从左上角到右下角的最短路线。

Input

一个5 × 5的二维数组,表示一个迷宫。数据保证有唯一解。

Output

左上角到右下角的最短路径,格式如样例所示。

Sample Input

0 1 0 0 0
0 1 0 1 0
0 0 0 0 0
0 1 1 1 0
0 0 0 1 0

Sample Output

(0, 0)
(1, 0)
(2, 0)
(2, 1)
(2, 2)
(2, 3)
(2, 4)
(3, 4)
(4, 4)
最近在学BFS,代码参考了网上的模板
#include<cstdio>
#include<cstring>
#include<algorithm>
#include<queue>
#include<stack>
using namespace std;
int maze[8][8];
int vis[8][8];
int rcd[8][8];
struct node{
    int x;
    int y;
    int stepcnt;//最短路径,此题用不着
};
struct ans{
    int a,b;
};//保存结果
stack<ans>A;//输出顺序反了,故借用一下栈
node vs,vd;//入口和出口
int dir[][2]={{0,-1},{-1,0},{0,1},{1,0}};//方向
void in_put()
{
    memset(rcd,0,sizeof(rcd));
    memset(maze,-1,sizeof(maze));//由于在check函数检查状态结点是否合法时,并没有考虑越界问题,故maze数组要清为非0
    memset(vis,0,sizeof(vis));
    for(int i=1;i<=5;++i)
        for(int j=1;j<=5;++j)
            scanf("%d",&maze[i][j]);
            vs.x=1;vs.y=1;vs.stepcnt=0;//初始化入口和出口
            vd.x=5;vd.y=5;vd.stepcnt=0;
}
int getpath(int i,int j)//递归获得路径
{
    ans tmp;
    tmp.a=i-1;
    tmp.b=j-1;
    if(i==1&&j==1) {A.push(tmp); return 0;}
    if(rcd[i][j]==4) {A.push(tmp);getpath(i-1,j);}
    else if(rcd[i][j]==3) {A.push(tmp);getpath(i,j-1);}
    else if(rcd[i][j]==2) {A.push(tmp);getpath(i+1,j);}
    else {A.push(tmp);getpath(i,j+1);}
}
int check(node v)//检查结点的合法性
{
    if(!vis[v.x][v.y]&&!maze[v.x][v.y])//maze边界若不清为非0 ,检查合法性时应加上&&v.x<=5&&v.x>=1&&v.y<=5&&v.y>=1
    return 1;
    else return 0;

}
node next,now;//当前结点now,下一个结点next
void BFS(node vs)
{

    queue<node>Q;
    Q.push(vs);//入口入队
    vs.stepcnt=0;//初始路径为0
    vis[vs.x][vs.y]=1;//入口结点标记已使用
    while(!Q.empty()){
        now=Q.front();
        if(now.x==vd.x&&now.y==vd.y) return;//达到出口
        for(int i=0;i<4;++i){//尝试四个方向
            next.x=now.x+dir[i][0];
            next.y=now.y+dir[i][1];
            next.stepcnt=now.stepcnt+1;
            if(check(next)){//检查结点的合法性
                rcd[next.x][next.y]=i+1;//记录完整路径中该结点到达上一个结点的方向 1:右  2:下  3:左  4:上
                vis[next.x][next.y]=1;//使用标记
                Q.push(next);//入队
            }
        }
        Q.pop();//队首出队
    }
}
int main()
{
    in_put();
    BFS(vs);
    getpath(5,5);//从出口回溯到入口
    while(!A.empty()){
        printf("(%d, %d)
",A.top().a,A.top().b);
        A.pop();
    }
}

原文地址:https://www.cnblogs.com/orchidzjl/p/4363137.html