poj 3984 迷宫问题

本文介绍了一种求解迷宫最短路径的算法实现,通过递归方式找到从起点到终点的所有可能路径,并筛选出最短的一条。使用C++编程语言实现,通过宽度优先搜索(BFS)算法来解决5x5迷宫问题。

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

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)

思路
递归打印路径

/*************************************************************************
    > File Name: poj3984.cpp
    > Author:ukiy 
    > Mail: 
    > Created Time: 20161203日 星期六 203257************************************************************************/

#include<iostream>
#include<cstdio>
#include<algorithm>
#include<cmath>
#include<cstdlib>
#include<climits>
#include<string>
#include<cstring>
#include<vector>
#include<set>
#include<list>
#include<map>
#include<queue>
int dire[4][2]={ {0,1},{1,0},{0,-1},{-1,0} };
int dire2[8][2]={{-1,-1},{-1,0},{-1,1},{ 0,-1},{ 0,1},{ 1,-1},{ 1,0},{ 1,1}};
#define rep(i,a,b) for(int i=(a);i<=(b);(i++))
#define inf 0x3f3f3f
#define ll long long
#define pi acos(-1)
int dire3[6][3]={ {0,0,1},{0,1,0},{1,0,0},{0,0,-1},{0,-1,0},{-1,0,0} };
using namespace std;
const int maxn=5; 
int a[maxn][maxn];//标记(x,y)是否遍历过
struct node{
    int x,y,pre;     //pre是在打印最短路径时标记当前node 上一个在q数组中的下标
}q[maxn];


void Print(int i){//递归打印路径
    if(q[i].pre!=-1){
        Print(q[i].pre);
        printf("(%d, %d)\n",q[i].x,q[i].y);
    }
}
void bfs(int cx,int cy){
    int front=0,rear=1,px,py;
    q[front].x=cx;
    q[front].y=cy;
    q[front].pre=-1;
    while(front < rear){
        rep(i,0,3){
            px=q[front].x+dire[i][0];
            py=q[front].y+dire[i][1]; 
            if(px<0||px>4||py<0||py>4||a[px][py]) //剪枝
                continue;
            else{
                a[px][py]=1;
                q[rear].x=px;
                q[rear].y=py;
                q[rear].pre=front;
                rear++;
            }
            if(px==4&&py==4)
                Print(front);
        }   
        front++;
    }

}
int main()
{
    std::ios::sync_with_stdio(false);
    #ifndef OnlineJudge
    //freopen("in.txt","r",stdin);
    //freopen("out.txt","w",stdout);
    #endif
    int i,j,k,m,n;
    memset(a,0,sizeof(a));
    rep(i,0,4){
        rep(j,0,4){
            cin>>a[i][j];
        }
    }
    printf("(0, 0)\n");
    bfs(0,0);
    printf("(4, 4)\n");
    return 0;
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值