POJ_3984 迷宫问题(广搜)

题目来源:http://poj.org/problem?id=3984

题目大意:给你一个5*5的迷宫,让你从左上角走到右下角,求最短路径,并将路径输出。

源代码:

/**********************************
**********广度优先搜索************
***********************************/
#include<cstdio>
#include<cstdlib>
#include<cmath>
#include<cstring>
#include<string>
#include<algorithm>
#include<stack>
#include<queue>
#include<map>

using namespace std;
#define N 5
int maze[N][N];//maze用来记录迷宫的形状
int visited[N][N];//flag用来记录该点有没有走过
int dir[4][2] = { 0,1,1,0,0,-1,-1,0};
struct pos{
    int x;
    int y;
    int pre;
}que[100];//用一个队列来存储路径

void print( int head)
{
    if( que[head].pre != -1)
    {
        print(que[head].pre);
        printf("(%d, %d)\n",que[head].x,que[head].y);
    }
}

void bfs( int x, int y)
{
    int head = 0;//队头
    int tail = 0;//队尾
    //将当前x、y入队
    que[head].x = x;
    que[head].y = y;
    que[head].pre = -1;
    visited[x][y] = 1;
    //队尾++
    tail++;

    int tx;
    int ty;
    while( head < tail)
    {
        for( int i = 0; i < 4; i++)
        {
            tx = que[head].x+dir[i][0];//分别向上下左右四个方向搜索
            ty = que[head].y+dir[i][1];
            //判断有没有出界
            if( tx < 0 || tx > N-1 || ty < 0 || ty > N-1)
                continue;
            //如果有路并且没有走过
            if( maze[tx][ty] == 0 && visited[tx][ty] == 0)
            {
                visited[tx][ty] = 1;//走这个点
                que[tail].x = tx;//将tx、ty入队
                que[tail].y = ty;
                que[tail].pre = head;//从head拓展出来的
                tail++;
            }

            if( tx == 4 && ty == 4)
            {
                print(head);
                return;
            }
        }
        head++;//当前head指向的拓展完之后往后走
    }

}

int main()
{
    memset(visited,0,sizeof(visited));//初始化

    for( int i = 0; i < N; i++)
        for( int j = 0; j < N; j++)
            scanf("%d",&maze[i][j]);

    printf("(0, 0)\n");
    bfs(0,0);
    printf("(4, 4)\n");

    return 0;
}


  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
程序在VC++ 6下顺利编译通过。 一、 实验目的: (1) 熟练掌握链栈的基本操作及应用。 (2) 利用链表作为栈的存储结构,设计实现一个求解迷宫的非递归程序。 二、实验内容: 【问题描述】 以一个m×n的长方阵表示迷宫,0和1分别表示迷宫中的通路和障碍。设计一个程序,对信任意设定的迷宫,求出一条从入口到出口的通路,或得出没有通路的结论。 【基本要求】 首先实现一个链表作存储结构的栈类型,然后编写一个求解迷宫的非递归程序。求得的通路以三元组(i,j,d)的形式输出,其中:(i,j)指示迷宫中的一个坐标,d表示走到下一坐标的方向。如:对于下列数据的迷宫,输出的一条通路为:(1,1,1),(1,2,2),(2,2,2),(3,2,3),(3,1,2),……。 【测试数据】 迷宫的测试数据如下:左上角(1,1)为入口,右下角(8,9)为出口。 1 2 3 4 5 6 7 8 0 0 1 0 0 0 1 0 0 0 1 0 0 0 1 0 0 0 0 0 1 1 0 1 0 1 1 1 0 0 1 0 0 0 0 1 0 0 0 0 0 1 0 0 0 1 0 1 0 1 1 1 1 0 0 1 1 1 0 0 0 1 0 1 1 1 0 0 0 0 0 0 以方阵形式输出迷宫及其通路。 输出: 请输入迷宫的长和宽:5 5 请输入迷宫内容: 0 1 1 0 0 0 0 1 1 0 1 0 0 1 1 1 0 0 1 0 1 1 0 0 0 迷宫的路径为 括号内的内容分别表示为(行坐标,列坐标,数字化方向,方向) (1,1,1,↓) (2,1,2,→) (2,2,1,↓) (3,2,1,↓) (4,2,2,→) (4,3,1,↓) (5,3,2,→) (5,4,2,→) (5,5,0,) 迷宫路径探索成功!
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值