SDNUOJ——1086.迷宮問題(BFS || DFS)

問題蟲洞:1086.迷宮問題

 

思維光年:

1、bfs標記路徑

2、dfs回溯

由於對bfs個dfs遍歷的過程還不是很理解,故此寫一篇基礎博客。。。

深度優先搜索(DFS)加回溯。(stack)

其優點:無需像廣度優先搜索那樣(BFS)記錄前驅結點。

其缺點:找到的第一條可行路徑不一定是最短路徑,

如果需要找到最短路徑,那麼需要找出所有可行路徑後,再逐一比較,求出最短路徑。

廣度優先搜索(BFS)(queue)

其優點:找出的第一條路徑就是最短路徑。

其缺點:需要記錄結點的前驅結點,來形成路徑。

 

DFS推薦博客:DFS——迷宮問題

BFS的代碼

//#include<bits/stdc++.h>
#include  <stdio.h>
#include <iostream>
#include<algorithm>
#include      <map>
#include      <set>
#include   <vector>
#include    <queue>
#include    <stack>
#include <stdlib.h>
#include  <cstring>
#include <string.h>
#include   <string>
#include   <math.h>
using namespace std;
typedef long long ll;
#define MAXN 1000007
#define INF 0x3f3f3f3f//將近ll類型最大數的一半,而且乘2不會爆ll

struct node
{
    int x, y, pre;///pre原來標記前一個結點
} g[30];
//queue<node>q;
int is[6][6], m[6][6];///is判斷是否訪問過該點,m是圖
int f[4][2] = {{1, 0}, {0, 1}, {-1, 0}, {0, -1}};

void print(int head)
{
    while(g[head].pre!=-1)
    {
        print(g[head].pre);
        printf("(%d, %d)\n", g[head].x, g[head].y);
        return;
    }
}

void bfs(int x, int y)
{
    int head=0, tail=0;
    g[tail].x = x;
    g[tail].y = y;
    g[tail].pre = -1;
    //is[x][y] = 1;
    tail++;
    node ans;
    while(head < tail)///隊列非空
    {
        if(g[head].x == 4 && g[head].y == 4)///終止條件
        {
            print(head);
            return;
        }
        for(int i=0; i<4; ++i)///上下左右遍歷該點的周圍點
        {
            ans.x = g[head].x + f[i][0];
            ans.y = g[head].y + f[i][1];
            ans.pre = head;
            if(ans.x>=0 && ans.x<=4 && ans.y >=0 && ans.y <=4)
            {
                if(is[ans.x][ans.y]!=1 && m[ans.x][ans.y]!=1)
                {
                    is[ans.x][ans.y] = 1;
                    g[tail++] = ans;
                }
            }
        }
        head++;///該點出隊
    }
}

int main()
{
    for(int i=0; i<5; ++i)
        for(int j=0; j<5; ++j)
            scanf("%1d", &m[i][j]);
    printf("(0, 0)\n");
    bfs(0, 0);
    return 0;
}

 

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