POJ 3984 BFS

迷宫问题
Time Limit: 1000MS   Memory Limit: 65536K
Total Submissions: 20665   Accepted: 12100

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)

Source

代码:

#include<iostream>
#include<cstdio>
#include<cstring>
#include<queue>
using namespace std;
int mp[8][8],vis[8][8];
int dir[4][2]={1,0,-1,0,0,1,0,-1};
struct node{
    int x,y;
    node(int a,int b):x(a),y(b){}
    node(){}
}pre[8][8],no;
void bfs()
{
    queue<node>q;
    q.push(node(0,0));
    while(!q.empty()){
        no=q.front();q.pop();
        for(int i=0;i<4;i++){
            int x=no.x+dir[i][0],y=no.y+dir[i][1];
            if(x<0||x>=5||y<0||y>=5||mp[x][y]) continue;
            if(vis[x][y]) continue;
            vis[x][y]=1;
            q.push(node(x,y));
            pre[x][y]=node(no.x,no.y);
            if(x==4&&y==4) return;
        }
    }
}
int main()
{
    for(int i=0;i<5;i++)
        for(int j=0;j<5;j++) 
            scanf("%d",&mp[i][j]);
    memset(vis,0,sizeof(vis));
    bfs();
    int ans[20],cnt=0,x=4,y=4;
    while(1){
        ans[++cnt]=x;
        ans[++cnt]=y;
        if(x==0&&y==0) break;
        int xx=x,yy=y;
        x=pre[xx][yy].x;
        y=pre[xx][yy].y;
    }
    for(int i=cnt;i>=1;i-=2)
        printf("(%d, %d)
",ans[i-1],ans[i]);
    return 0;
}
原文地址:https://www.cnblogs.com/--ZHIYUAN/p/6675774.html