《微服务架构核心精解二十讲》目前最新

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 <iostream>
#include <algorithm>
#include <cstdlib>
#include <cmath>
#include <cstring>
#include <cstdio>
#include <deque>
#include <queue>
#include <stack>
using namespace std;
typedef long long ll;
struct A
{
    ll s;
    ll e;
    ll time;//第几步
    ll per;//指向前一个在aa数组中的位置
    ll location;//当前在aa数组中的位置
}start,now,aa[30];
ll vis[5][5];
ll a[5][5];
stack <A> st;
ll dir[4][2]={-1,0,1,0,0,1,0,-1};
queue <A> q;
void bfs(ll x,ll y)
{
    while(!q.empty())
        q.pop();
    while(!st.empty())
        st.pop();
    ll i,j,e=0;
    memset(vis,0,sizeof(vis));
    start.s=x;
    start.e=y;
    start.time=0;
    vis[x][y]=1;
    start.location=0;
    start.per=-1;
    q.push(start);
    aa[0]=start;//先将第一个放入数组中,这个aa数组里面的位置没有固定的位置,有per可以确定
    e=1;
    while(!q.empty())
    {
        now=q.front();
        q.pop();
        if(now.s==4&&now.e==4)//满足时将结果放入栈中
        {
            ll t;
            A w=now;
            st.push(w);//终点放入栈中
            while(1)
            {
                t=w.per;
                if(t==-1)//表示已经到起点了
                    break;
                w=aa[t];
                st.push(w);
            }
        }
        for(i=0;i<4;i++)
        {
            start.s=now.s+dir[i][0];
            start.e=now.e+dir[i][1];
            start.time=now.time+1;
            if(start.s>=0&&start.s<=4&&start.e>=0&&start.e<=4&&vis[start.s][start.e]==0&&a[start.s][start.e]!=1)
            {
                start.location=e;
                start.per=now.location;//将现在位置的per指向上一步
                vis[start.s][start.e]=1;
                q.push(start);
                aa[e++]=start;//放到aa数组中,per,location是记录位置信息的
            }
        }
    }
    return ;
}
int main()
{
    ll i,j,ans;
    for(i=0;i<5;i++)
        for(j=0;j<5;j++)
            cin>>a[i][j];
    bfs(0,0);
    while(!st.empty())
    {
        start=st.top();
        cout<<"("<<start.s<<", "<<start.e<<")"<<endl;
        st.pop();
    }
    return 0;
}
 


--------------------- 
作者:__zcy 
来源:CSDN 
原文:https://blog.csdn.net/ZCY19990813/article/details/88875625 
版权声明:本文为博主原创文章,转载请附上博文链接!

猜你喜欢

转载自blog.csdn.net/renwuy/article/details/89208185