POJ 3984 迷宫问题 记录路径的广搜

主要是学一下如何在广搜中记录路径:每找到一个点我就记录下这个点是由那个点得来的,这样我找到最后个点后,我就可以通过回溯得到我走过的路径,具体看代码吧~

#include<cstdio>
#include<stdio.h>
#include<cstdlib>
#include<cmath>
#include<iostream>
#include<algorithm>
#include<cstring>
#include<vector>
#include<queue>
#define INF 0x3f3f3f3f
#define MAX 1005

using namespace std;

int Map[MAX][MAX],n,v[4][2]={{0,1},{0,-1},{1,0},{-1,0}};

struct node
{
    int x,y,step;
}ans[MAX][MAX];

void Ans(int x,int y)
{
    node put[100];
    int k=1,a,b;
    while(x!=0 || y!=0)//通过回溯的过程得到我走过的路径
    {
        a=x;
        b=y;
        put[k].x=ans[x][y].x;
        put[k++].y=ans[x][y].y;

        x=ans[a][b].x;
        y=ans[a][b].y;
    }

    for(int i=k-1;i>=1;i--)
    {
        printf("(%d, %d)\n",put[i].x,put[i].y);
    }
    printf("(4, 4)\n");
}

void BFS()
{
    queue<node>Q;
    node a,next;
    a.x=0;
    a.y=0;
    a.step=0;
    Q.push(a);
    Map[0][0]=1;

    while(!Q.empty())
    {
        a=Q.front();
        Q.pop();

        if(a.x==4 && a.y==4)
        {
            Ans(4,4);
            return;
        }

        for(int i=0;i<4;i++)
        {
            next.x=a.x+v[i][0];
            next.y=a.y+v[i][1];

            if(next.x>=0 && next.x<5 && next.y>=0 && next.y<5 && Map[next.x][next.y]==0)
            {
                Map[next.x][next.y]=1;
                next.step=a.step+1;
                ans[next.x][next.y].x=a.x;//记录上一个点
                ans[next.x][next.y].y=a.y;
                Q.push(next);
            }
        }
    }
}

int main()
{
    int i,j;

    for(i=0;i<5;i++)
    for(j=0;j<5;j++)
    scanf("%d",&Map[i][j]);

    BFS();

    return 0;
}
View Code

由于POJ上只有一组数据,你的代码就算A了也不一定正确,下面给出几组数据吧。

输入:
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

0 0 0 0 0
0 1 1 1 0
0 1 0 0 0
0 1 1 1 0
0 0 0 1 0

0 0 0 0 0
0 1 1 1 0
0 1 0 0 0
0 0 1 0 1
1 0 0 0 0


0 0 0 0 0
0 1 1 1 0
1 0 0 0 0
1 0 1 0 1
1 0 0 0 0

输出:
(0, 0)
(1, 0)
(2, 0)
(2, 1)
(2, 2)
(2, 3)
(2, 4)
(3, 4)
(4, 4)

(0, 0)
(0, 1)
(0, 2)
(0, 3)
(0, 4)
(1, 4)
(2, 4)
(3, 4)
(4, 4)

(0, 0)
(1, 0)
(2, 0)
(3, 0)
(3, 1)
(4, 1)
(4, 2)
(4, 3)
(4, 4)

(0, 0)
(0, 1)
(0, 2)
(0, 3)
(0, 4)
(1, 4)
(2, 4)
(2, 3)
(3, 3)
(4, 3)
(4, 4)
posted @ 2016-07-16 15:07  声声醉如兰  阅读(1241)  评论(0)    收藏  举报