zoukankan      html  css  js  c++  java
  • poj迷宫问题

    poj迷宫问题

    #include <iostream>
    
    using namespace std;
    int map[6][6];
    const int x_[4]={0,0,1,-1},y_[4]={1,-1,0,0};//每个节点有四个方向可以用来遍历
    struct node
    {
        int x,y,pre;
    }p[100];
    int front=0,sumofnodes=1;//front是走的路径的长度,sumofnodes是探测到的节点数目
    void print(int temp)//递归输出路径
    {
        if(p[temp].pre!=-1)
        {
            print(p[temp].pre);
            cout<<"("<<p[temp].x<<", "<<p[temp].y<<")"<<endl;
        }
    }
    void bfs(int x,int y)
    {
        p[front].x=x;
        p[front].y=y;
        p[front].pre=-1;
        while(front<sumofnodes)//走的路径个数要小于节点的个数
        {
            for(int i=0;i<4;i++)//向四个方向便利,把为走过的节点放到队列里面
            {
                int a=p[front].x+x_[i];
                int b=p[front].y+y_[i];
                if(a<0||a>=5||b<0||b>=5||map[a][b])//边界条件
                    continue;
                else
                   {
                       map[a][b]=1;
                       p[sumofnodes].x=a;
                       p[sumofnodes].y=b;
                       p[sumofnodes].pre=front;//保存下路径的长度,以便最后递归可以正常运行
                       sumofnodes++;
                   }
                if(a==4&&b==4)//下一个节点是出口
                    print(front);
            }
            front++;
        }
    }
    int main()
    {
        for(int i=0;i<5;i++)
        {
            for(int j=0;j<5;j++)
            {
                cin>>map[i][j];
            }
        }
        cout<<"(0, 0)"<<endl;
        bfs(0,0);
        cout<<"(4, 4)"<<endl;
    }
    

    用bfs一层一层的进行搜索,用递归输出结果,还是不错的bfs入门题

    新的博客地址 kele1997.xyz 博客园可能不会更新了
  • 相关阅读:
    Tye exception
    DataSeeder
    angular
    认证Authentication
    MVC
    Ef Core
    工作单元
    VirtualFileSystem
    中间件
    日志
  • 原文地址:https://www.cnblogs.com/kele1997/p/6810327.html
Copyright © 2011-2022 走看看