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;
}
    原文作者:迷宫问题
    原文地址: https://blog.csdn.net/u011558005/article/details/17612593
    本文转自网络文章,转载此文章仅为分享知识,如有侵权,请联系博主进行删除。
点赞