poj 3984迷宫问题

<span style="font-size: 18pt; font-family: Arial, Helvetica, sans-serif; background-color: rgb(255, 255, 255);">迷宫问题</span>
Time Limit: 1000MS Memory Limit: 65536K
Total Submissions: 7610 Accepted: 4463

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

简单bfs,用一个Pre数组来记录路径,起到的是一个类似指针的作用。

#include<algorithm>
#include<iostream>
#include<cstdio>
#include<cstring>
using namespace std;
struct node
{
    int x;
    int y;
};
node road[25];
bool vis[10][10];
int head , tail;
int dir[4][2]={{-1,0},{1,0},{0,-1},{0,1}};
int Map[10][10];
int pre[100]; 
bool ok(int x, int y)  ///判断当前结点是否可达
{
    if(x >= 0 && x < 5 && y >= 0 && y < 5 && Map[x][y] == 0 && vis[x][y] == 0)
        return 1;
    return 0;
}
void print(int x) ///输出路径
{
    if(pre[x] != -1) ///pre[x]不为-1,则说明该结点有父节点,即在到达该点之前还有其他路径
    {
        print(pre[x]);
        printf("(%d, %d)\n", road[x].x , road[x].y);
    }
}
void bfs()
{
    int head , tail, x, y, xx, yy;  ///head起到的是一个父节点的作用
    memset(vis, 0, sizeof(vis));
    head = 0;
    tail = 1;
    road[head].x = 0;
    road[head].y = 0;
    pre[head] = -1;
    while(head < tail) ///判断队列是否为空
    {
        x = road[head].x;
        y = road[head].y;
        if(x == 4 && y == 4)
        {
            print(head);
            return ;
        }
        for(int i=0; i<4; ++i)
        {
            xx = x + dir[i][0];
            yy = y + dir[i][1];
            if(ok(xx , yy))
            {
                vis[xx][yy] = 1;
                road[tail].x = xx;
                road[tail].y = yy;
                pre[tail] = head; ///记录该结点的父节点
                tail++; 
            }
        }
        head++;
    }
}
int main()
{
    for(int i=0; i<5; ++i)
        for(int j=0; j<5; ++j)
            scanf("%d", &Map[i][j]);
    printf("(0, 0)\n");
    bfs();
    return 0;
}


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值