poj3984迷宮問題(bfs帶路徑)

迷宮問題
Time Limit: 1000MS   Memory Limit: 65536K
Total Submissions: 6576   Accepted: 3844

Description

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

Input

一個5 × 5的二維數組,表示一個迷宮。數據保證有唯一解。

Output

左上角到右下角的最短路徑,格式如樣例所示。

Sample Input

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

Sample Output

(0, 0)
(1, 0)
(2, 0)
(2, 1)
(2, 2)
(2, 3)
(2, 4)
(3, 4)
(4, 4)


#include <iostream>
#include <cstring>
#include <queue>
using namespace std;
//節點
class node{
public:
    int x,y;
    bool operator == (const node &b){
        return (x==b.x && y==b.y);
    }
};
//地圖 前一個節點 該節點是否被訪問
int mat[5][5], pre[25]; bool vis[25];
//四個方向
int dir[4][2]={
    {-1, 0},
    {0, -1},
    {0, 1},
    {1, 0}
};
void bfs(node a, node b){
    queue<node> Q;
    memset(vis,false,sizeof(vis));
    memset(pre,-1,sizeof(pre));
    int Q_size;
    node head, next;
    vis[a.x*5+a.y] = true;
    pre[0] = -1;
    Q.push(a);
    while(!Q.empty()){
        Q_size = Q.size();
        while(Q_size--){
            head = Q.front();
            Q.pop();
            if(head==b) return;
            for(int i=0; i<4; i++){
                next.x = head.x + dir[i][0];
                next.y = head.y + dir[i][1];
                if(next.x<0 || next.x>4 || next.y<0 || next.y>4 || mat[next.x][next.y] || vis[next.x*5+next.y])
                    continue;
                vis[next.x*5+next.y] = true;
                pre[next.x*5+next.y] = head.x*5+head.y;
                Q.push(next);
            }
        }
    }
}

void print(int pre[], int n){
    if(pre[n]!=-1)
        print(pre,pre[n]);
    cout<<"("<<n/5<<", "<<n%5<<")"<<endl;
}

int main()
{
    for(int i=0; i<5; i++)
        for(int j=0; j<5; j++) cin>>mat[i][j];
    node a,b;
    a.x = a.y = 0;
    b.x = b.y = 4;
    bfs(a,b);
    print(pre,24);
    return 0;
}


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