poj-3984-迷宫问题

原文链接 :poj-3984-迷宫问题

原题:
迷宫问题
Time Limit: 1000MS Memory Limit: 65536K
Total Submissions: 25699 Accepted: 14956
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)

问题分析:对于迷宫问题,可以用dfs也可以用bfs,该题所求的是路径最短的解,使用bfs求出的解既是 最短的解。

AC代码:

#include<iostream>
#include<queue>
#include<cstring>
using namespace std;
const int maxn=5,directsize=4,sx=0,sy=0,ex=4,ey=4;
struct dir{ //转方向 
    int x,y;
}dir[directsize]={{0,1},{0,-1},{1,0},{-1,0}};
struct node //存放点的坐标 
{
    int x,y;
};
int arr[maxn+1][maxn+1];
int vis[maxn+1][maxn+1]={0};
node father[maxn+1][maxn+1],path[maxn*maxn]; //用于输出 
queue<node>q;

void result_cout()//先逆序存入到path数组中,再正序输出 
{
    int count=0;
    path[count].x=ex;
    path[count].y=ey;


    for(;;)
    {
        if(path[count].x==sx&&path[count].y==sy)
            break;
        path[count+1]=father[path[count].x][path[count].y];
        count++;
    }
    for(int i=count;i>=0;i--)
        cout<<"("<<path[i].x<<", "<<path[i].y<<")"<<endl;
}

void bfs()
{
    int i;
    memset(vis,0,sizeof(vis));

    node start,front,v;
    start.x=sx;start.y=sx;
    q.push(start);
    vis[start.x][start.y]=1;

    while(!q.empty())
    {
        front=q.front();
        q.pop();

        if(front.x==ex&&front.y==ey)
        {
            result_cout();
            return ;
        }

        for(i=0;i<directsize;i++)
        {
            v.x=front.x+dir[i].x;
            v.y=front.y+dir[i].y;

            if(v.x<0||v.x>=maxn||v.y<0||v.y>=maxn||arr[v.x][v.y]||vis[v.x][v.y])
                continue;

            q.push(v);

            father[v.x][v.y]=front;

        }
        vis[front.x][front.y]=1;
    }
}

int main()
{
    int i,j;
    for(i=0;i<maxn;i++)
        for(j=0;j<maxn;j++)
            cin>>arr[i][j];
    bfs();  

    return 0;
} 
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值