zoukankan      html  css  js  c++  java
  • 宽度优先搜索(BFS)

    宽度优先搜索,又称为广度优先搜索,简称BFS

    搜索过程:从初始结点开始,逐层向下扩展,即第n层搜索未完成,不得进入下一层搜索

    一、初始结点入队,进入循环

    二、取出队列的第一个元素

    三、判断该结点是不是目标结点,如果是目标结点,则问题解决,跳出循环

    四、如果该结点不是目标结点,判断其是否能够扩展,若不能,跳到步骤二

    五、如果该结点能扩展,将其子结点放入队列的尾部

    六、跳到步骤二

    用一个经典的例子(走迷宫)来感受下

    给定一个二维数组 int a[10][10] = {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”代表通路,只能横着走或竖着走,要求编写程序找出从左上角到右下角的最短路径的长度

    #include<iostream>
    
    using namespace std ;
    
    int dx[] = {-1,0,1,0} ;
    int dy[] = {0,1,0,-1} ;
    
    int m , n ;
    
    int map[10][10] ;
    
    int visit[10][10] = {0} ;
    
    typedef struct Node {
        int x , y ;
        int step ;
    }Node;
    
    bool is_ok(Node cur)    {
        if(cur.x < 0 || cur.x >= m || cur.y < 0 || cur.y >= n)
            return false ;
        return true ;
    }
    
    void bfs()    {
        Node node[1000] ;
        int first , last ;
        first = last = 0 ;
        Node cur ;
        cur.x = 0 , cur.y = 0 ; cur.step = 0 ;
        node[last++] = cur ;
        visit[0][0] = 1 ;
        while(first < last)    {
            cur = node[first++] ;
            if(cur.x == 4 && cur.y == 4)    {
                cout << cur.step << endl ;
                break ; 
            }
            for(int i = 0 ; i < 4 ; i++)    {
                Node next ;
                next.x = cur.x + dx[i] ;
                next.y = cur.y + dy[i] ;
                if(map[next.x][next.y] == 1)
                    continue ;
                if(visit[next.x][next.y] == 1)
                    continue ;
                if(is_ok(next) == true)    {
                    next.step = cur.step + 1 ;
                    visit[next.x][next.y] = 1 ;
                    node[last++] = next ;
                }
            }
        }
    }
    
    int main()    {
        cin >> m >> n ;
        for(int i = 0 ; i < m ; i++)
            for(int j = 0 ; j < n ; j++)
                cin >> map[i][j] ;
        bfs() ;
        return 0 ;
    }
  • 相关阅读:
    带勾选框的组织F4
    VBA 学习
    MACD指标量化策略实战案例
    DOM
    JS基础下
    JS基础
    CSS基础
    html实战4--transform3D
    html实战3--精灵图
    html实战2--四叶草
  • 原文地址:https://www.cnblogs.com/scottdinggo/p/4440153.html
Copyright © 2011-2022 走看看