迷宫问题

这个题目比较模板化吧,所以bfs肯定能做出来,但是四个方向的这个数组的函数判断,真的有点懵逼,可能是我还没有怎么思考,但是别的地方还是有思路的,首先还是之前提过的bfs遍历,但是在遍历的时候要使用队列,这个队列可以是一个结构体,里面可以存横坐标和纵坐标,然后还是那两个数组,如果有符合条件的坐标,就铺设到这个队列里面,然后我们最后用vector函数库里面的函数,逐个打印

#include<stack>
#include<cstring>
#include<vector>
#include<cstdio>
using namespace std;
struct  node
{
   int a,b;
};
int maze[7][7];
bool vis[7][7];
stack<node>  passby;
int n;
void init()
{
   memset(vis,0,sizeof(vis));

   for(int i=0;i<7;i++)
    {
       maze[i][0]=1;
       maze[0][i]=1;
       maze[6][i]=1;
       maze[i][6]=1;
    }
}
void dfs(int x,int y)
{
    if(!vis[x][y])
    {
        node cur;
        cur.a=x;
        cur.b=y;
        vis[x][y]=1;
        passby.push(cur);
    }

    if(x==5&&y==5)   return ;

        if(!vis[x+1][y]&&!maze[x+1][y]) dfs(x+1,y);
        else if(!vis[x][y+1]&&!maze[x][y+1]) dfs(x,y+1);
        else
        {
           passby.pop();
           node cur=passby.top();
           dfs(cur.a,cur.b);
        }
}
int main()
{
   for(int i=1;i<=5;i++)
     for(int j=1;j<=5;j++)
        scanf("%d",&maze[i][j]);
   init();
   dfs(1,1);
   vector<node>  v;
   while(passby.empty()==false)
   {
       v.push_back(passby.top());
       passby.pop();
   }
   for(int i=v.size()-1;i>=0;i--)
   {
       printf("(%d, %d)
",v[i].a-1,v[i].b-1);
   }
}

  

原文地址:https://www.cnblogs.com/yintoki/p/5676787.html