C++算法——BFS(圖解)

簡介

寬度優先搜索算法(又稱廣度優先搜索)是最簡便的圖的搜索算法之一,這一算法也是很多重要的圖的算法的原型。其別名又叫BFS,屬於一種盲目搜尋法,目的是系統地展開並檢查圖中的所有節點,以找尋結果。換句話說,它並不考慮結果的可能位置,徹底地搜索整張圖,直到找到結果爲止。

相信初次接觸的人已經蒙圈了,那麼我們先不要探究其代碼,直接從這個算法的過程來觀察它怎樣運算

BFS常用於迷宮,即從一點到另一點的最短路徑,所以這裏以一個迷宮來說明:

這裏有一個5*5的迷宮,1是牆,0是路,那麼從左上角走道右下角最少需要多少步呢?
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
首先把終點設爲3,走過的路設爲2,可以得到這樣的過程圖:
在這裏插入圖片描述
從圖中可以清楚地看到這個算法從(0,0)點開始,向不同方向走,到達指定條件就停止並返回結果

就是因爲這個性質,先到達的那條路線一定是步數最少的,所以只要有一條路線走到了,那麼它一定就是最短路線,直接返回,所以這個算法非常快(重點!重點!重點!)

代碼

這就是上面那個問題的代碼(帶打印地圖)

#include <iostream>
#include <cstdio>
#include <queue>
using namespace std;
int Map[5][5];  //定義地圖大小
int dir[4][2]= {1,0,-1,0,0,-1,0,1};  //定義方向
int n,m,ans;
struct node
{
    int x,y,step;

} now,nextt;  //保存走步
int BFS(int x,int y)
{
    queue<node>q;
    int xx,yy,zz;
    Map[x][y]=2;  //走過初始點
    now.x=x;
    now.y=y;
    now.step=0;
    q.push(now);  //從當前點開始
    while(!q.empty())
    {
        now=q.front();
        q.pop();
        for(int i=0; i<4; i++)  //遍歷四個方向
        {
            xx=now.x+dir[i][0];
            yy=now.y+dir[i][1];  //走一步
            if(xx>=0&&xx<5&&yy>=0&&yy<5&&Map[xx][yy]!=1&&Map[xx][yy]!=2)  //可以走
            {
                nextt.x=xx;
                nextt.y=yy;
                nextt.step=now.step+1;  //步數加一
                Map[now.x][now.y]=2;   //走過一個點
                if(Map[xx][yy]==3)  //到達終點
                    return nextt.step;
                q.push(nextt);

            }
            for(int i=0; i<5; i++){      //打印地圖
                for(int j=0; j<5; j++)
                    cout << Map[i][j];
                cout << endl;
            }
            cout << endl;
        }
    }
    return -1;   //走不過去
}

int main()
{

    for(int i=0; i<5; i++)     //輸入地圖
        for(int j=0; j<5; j++)
            cin >> Map[i][j];
    Map[4][4]=3;  //定義終點
    ans=BFS(0,0);
    cout << ans<< endl;
    return 0;

}

以上就是一個簡單的BFS模板

例題

1.首先來看一個迷宮問題的變種

HDU-1072
這個問題相當於添加了步數限制,只需要把上面改動一下過程

#include <iostream>
#include <cstdio>
#include <queue>
using namespace std;
const int maxn=200;
int Map[maxn][maxn];
int dir[4][2]= {1,0,-1,0,0,-1,0,1};
int n,m,ans;
struct node
{
    int x,y,step,z;

} now,nextt;
int BFS(int x,int y,int z)
{
    queue<node>q;
    int xx,yy,zz;
    Map[x][y]=0;
    now.x=x;
    now.y=y;
    now.step=0;
    now.z = z;
    q.push(now);
    while(!q.empty())
    {
        now=q.front();
        q.pop();
        for(int i=0; i<4; i++)
        {
            xx=now.x+dir[i][0];
            yy=now.y+dir[i][1];
            zz = now.z-1;
            if(xx>=0&&xx<n&&yy>=0&&yy<m&&Map[xx][yy]!=0 && (zz>1 || (Map[xx][yy]!=1 && zz==1)))
            {
                nextt.x=xx;
                nextt.y=yy;
                nextt.step=now.step+1;
                nextt.z = zz;
                if(Map[xx][yy]==4){
                    Map[xx][yy] = 0;
                    nextt.z = 6;
                }
                else if(Map[xx][yy]==3)
                    return nextt.step;
                q.push(nextt);

            }
        }
    }
    return -1;
}

int main()
{
    int sx,sy,o;
    cin >> o;
    while(o--)
    {
        cin >> n >> m;
        for(int i=0; i<n; i++)
        {
            for(int j=0; j<m; j++)
            {
                cin >> Map[i][j];
                if(Map[i][j]==2)
                {
                    sx=i;
                    sy=j;
                }
            }
        }
        ans=BFS(sx,sy,6);
        cout << ans<< endl;
    }
    return 0;

}

2.另一種變化

POJ - 1915
這個問題只需要在簡單模板的基礎上改一下走法就可以了

#include <iostream>
#include <cstdio>
#include <queue>
#include <cstring>
using namespace std;
const int maxn=301;
int Map[maxn][maxn];
int dir[8][2]= {-2,-1,-2,1,-1,2,1,2,2,1,2,-1,1,-2,-1,-2};
int l,sx,sy,lx,ly,o,ans;
struct node
{
    int x,y,step;

} now,nextt;
int BFS(int x,int y)
{
    queue<node>q;
    int xx,yy;
    Map[x][y]=1;
    now.x=x;
    now.y=y;
    now.step=0;
    q.push(now);
    while(!q.empty())
    {
        now=q.front();
        q.pop();
        for(int i=0; i<8; i++)  //注意八個方向
        {
            xx=now.x+dir[i][0];
            yy=now.y+dir[i][1];
            if(xx>=0&&xx<l&&yy>=0&&yy<l&&Map[xx][yy]!=1)
            {
                nextt.x=xx;
                nextt.y=yy;
                nextt.step=now.step+1;
                if(xx==lx && yy==ly)
                    return nextt.step;
                q.push(nextt);
                Map[xx][yy]=1;
            }
        }
    }
}

int main()
{
    cin >> o;
    while(o--)
    {
        cin >> l >> sx >> sy >> lx >> ly;
        memset(Map,0,sizeof(Map));
        if(sx==lx && sy==ly)
            ans = 0;
        else
            ans=BFS(sx,sy);
        printf("%d\n",ans);
    }
    return 0;

}

3.別的應用(連通塊)

POJ - 1562
注意方向和BFS運用方法改變

#include <iostream>
#include <queue>
#include <cstdio>
using namespace std;
const int maxn=105;
char Map[maxn][maxn];
int n,m,cnt=0;
int dir[8][2]={{1,0},{1,1},{1,-1},{-1,0},{-1,1},{-1,-1},{0,1},{0,-1}};
struct node
{
    int x;
    int y;
}now,next;
void BFS(int x,int y)
{
    now.x=x;
    now.y=y;
    Map[x][y]='*';
    queue<node> q;
    q.push(now);
    while(!q.empty())
    {
        now=q.front();
        q.pop();
        for(int i=0;i<8;i++)
        {
            int xx=now.x+dir[i][0];
            int yy=now.y+dir[i][1];
            if(xx>=0&&xx<n&&yy>=0&&y<m&&Map[xx][yy]=='@')
            {
                Map[xx][yy]='*';
                next.x=xx;
                next.y=yy;
                q.push(next);
            }
        }
    }
}
int main()
{
    while(~scanf("%d%d",&n,&m))
    {
        cnt=0;
        if(n==0)///輸入0 0 退出
            break;
        for(int i=0;i<n;i++)
        {
            scanf("%s",Map[i]);
        }
        for(int i=0;i<n;i++)
        {
            for(int j=0;j<m;j++)
            {
                if(Map[i][j]=='@')
                {
                    cnt++;
                    BFS(i,j);
                }
            }
        }
        printf("%d\n",cnt);
    }
    return 0;
}

以上舉了三個較簡單的例題,能完全明白就瞭解了BFS的基礎應用,還需要學會BFS的更多變種以及怎樣與別的算法結合

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章