poj 3984 迷宫问题(模拟队列)

本文介绍了一个迷宫问题的解决方案,通过使用BFS(宽度优先搜索)算法找到从迷宫左上角到右下角的最短路径,并详细展示了如何利用模拟队列记录路径及最终递归输出路径的过程。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

题目链接:http://poj.org/problem?id=3984


迷宫问题
Time Limit: 1000MS Memory Limit: 65536K
Total Submissions: 16573 Accepted: 9884

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

[Submit]   [Go Back]   [Status]   [Discuss]

Home Page   Go Back  To top




题目大意:略

解析:显然用BFS搜索,但本题要求输出路径,所以就要用模拟队列来记录路径,最后简单的递归输出路径


代码如下:

#include<iostream>
#include<algorithm>
#include<map>
#include<stack>
#include<queue>
#include<vector>
#include<set>
#include<string>
#include<cstdio>
#include<cstring>
#include<cctype>
#include<cmath>
#define N 4009
using namespace std;
const int inf = 1e9;
const int mod = 1<<30;
const double eps = 1e-8;
const double pi = acos(-1.0);
typedef long long LL;
int mp[6][6], vis[6][6];
int nx[6] = {-1, 0, 0, 1};
int ny[6] = {0, -1, 1, 0};

struct node
{
    int x, y, s;
}t[N];

void Display(int r)
{
    if(r == 0)
    {
        printf("(0, 0)\n"); return ;
    }
    Display(t[r].s);
    printf("(%d, %d)\n", t[r].x - 1, t[r].y - 1);
}

void solve()
{
    memset(vis, 0, sizeof(vis));
    int i, x, y;
    int s, e; s = e = 0;
    vis[1][1] = 1;
    t[s].x = t[s].y = 1; t[s].s = -1;
    while(s <= e)
    {
        if(t[s].x == 5 && t[s].y == 5) break;
        for(i = 0; i < 4; i++)
        {
            x = t[s].x + nx[i]; y = t[s].y + ny[i];
            if(x < 1 || y < 1 || x > 5 || y > 5) continue;
            if(vis[x][y] || mp[x][y]) continue;
            t[++e].x = x; t[e].y = y; t[e].s = s;
            vis[x][y] = 1;
        }
        s++;
    }
    Display(s);
}

int main()
{
    int i, j;
    for(i = 1; i <= 5; i++)
    {
        for(j = 1; j <= 5; j++)
            scanf("%d", &mp[i][j]);
    }
    solve();
    return 0;
}




评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值