廣度搜索bfs——百鍊10:迷宮問題

10:迷宮問題

總時間限制:
1000ms
內存限制:
65536kB
描述

定義一個二維數組:

int maze[5][5] = {

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表示可以走的路,只能橫着走或豎着走,不能斜着走,要求編程序找出從左上角到右下角的最短路線。


輸入
一個5 × 5的二維數組,表示一個迷宮。數據保證有唯一解。
輸出
左上角到右下角的最短路徑,格式如樣例所示。
樣例輸入
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
樣例輸出
(0, 0)
(1, 0)
(2, 0)
(2, 1)
(2, 2)
(2, 3)
(2, 4)
(3, 4)
(4, 4)

解題思路:
   利用結構體儲存當前的座標x,y和該點的前驅和本身pre,n;本題利用廣度搜索向每個可走的方向(這裏是四個方向,有的是八個方向)走一步,並記錄該點的座標前驅和本身,最後返回一個終點的本身(n,代表廣搜的第n個點),然後利用遞歸輸出前驅座標。

代碼實現:
#include <iostream>
#include <cstdio>
#include <cstring>
#include <queue>
#include <map>
#include <vector>
#include <set>
#include <cmath>
#include <algorithm>

using namespace std;

const int maxn = 30;
int mp[5][5];                                       // 地圖;
int vis[5][5]={0};                                  // 標記走過與否;
int dis[4][2] = { {0,1}, {0,-1}, {1,0}, {-1,0} };   // 可走的四個方向;

struct node                                         //記錄該點的信息;
{
    int x, y, pre, n;
}point[maxn];

int bfs()
{
    point[0] = { 0, 0, -1, 0 };
    int cnt=0;
    queue<node>q;
    q.push( point[0] );
    vis[0][0] = 1;
    while( !q.empty() )
    {
        node t = q.front();
        q.pop();                                         // 每次取隊列第一個元素並釋放;
        int nowx = t.x, nowy = t.y, now = t.n;
        if( nowx == 4 && nowy == 4)
            return now;
        for( int i=0; i<4; i++ )                         // 四個方向各走一次;
        {
            int gx = nowx + dis[i][0], gy = nowy + dis[i][1];
            if( gx >= 0 && gx < 5 && gy >= 0 && gy < 5 && !vis[gx][gy] && !mp[gx][gy])
            {
                point[++cnt] = { gx, gy, now, cnt};
                vis[gx][gy] = 1;                      // 標記該點走過;
                q.push(point[cnt]);                   // 將每次去得元素的可走路壓入隊列;
            }
        }
    }
}

void dfs( int d )
{
    if( point[d].n )
        dfs( point[d].pre );                             // 利用遞歸找到起點,依次遞歸輸出;
    printf("(%d, %d)\n" , point[d].x, point[d].y );
}

int main()
{
    int i, j;
    for( i=0; i<5; i++ )
        for( j=0; j<5; j++ )
            cin >> mp[i][j];
    int m =bfs();
    dfs(m);
    return 0;
}

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