迷宫问题,POJ-3984

定义一个二维数组: 

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)
  思路:搜索题(用广搜比较方便,因为还要记录信息),但是要输出每一步的经过哪个位置,使用结构体指针进行回溯输出每一步的信息。(也可以用其他方法存储信息,比如结构体数组,
一维数组之类的)。要注意,声明结构体指针时,要及时分配内存首地址,不然会报错,使用malloc函数。代码如下:
#include <iostream>
#include <stdlib.h>
#include <cstring>
#include <algorithm>
#include <queue>
#include <string.h>
using namespace std;
int dd[4][2]={1,0,0,1,-1,0,0,-1} ;
int mp[5][5];
int used[5][5];
struct node{
    int x,y;//坐标
    int step;//记录步数
    node *last;//结构体指针
};
bool judge(int x,int y)
{
    return x>=0&&x<5&&y>=0&&y<5;
}
node* bfs(int x,int y)
{
    memset(used,0,sizeof(used));
    node *s;
    s=(node *)malloc(sizeof(node));//注意分配内存
    s->x=x,s->y=y,s->step=0;
    s->last=NULL;
    queue<node *>q;
    q.push(s);
    while(!q.empty())
    {
        s=q.front();q.pop();
        if(s->x==4&&s->y==4)return s;
        for(int i=0;i<4;i++)
        {
            int nx=s->x+dd[i][0];
            int ny=s->y+dd[i][1];
            if(judge(nx,ny)&&used[nx][ny]==0&&mp[nx][ny]==0)
            {
                used[nx][ny]=1;
                node *e;//当某个点能走时,声明一个新的结构指针e,它的*last指向上一步(即s),如此重复下去,当走到终点时,进行回溯可得到每一步的信息。
                e=(node *)malloc(sizeof(node));
                e->x=nx,e->y=ny;
                e->step=s->step+1;
                e->last=s;
                q.push(e);
            }
        }
    }
    return NULL;
}
void output(node *s)
{
    if(s==NULL)return;
    output(s->last);
    printf("(%d, %d)\n",s->x,s->y);
}
int main()
{
    for(int i=0;i<5;i++)
    {
        for(int j=0;j<5;j++)
        {
            scanf("%d",&mp[i][j]);
        }
    }
    output(bfs(0,0));
    return 0;
}

猜你喜欢

转载自www.cnblogs.com/whocarethat/p/11107872.html