简单BFS +打印路径 迷宫问题 POJ - 3984

#include<cstdio>
#include<iostream>
#include<cstring>
#include<string>
#include<stack>
#include<queue>
using namespace std;
int nex[4][2]= { {0,1},{1,0},{0,-1},{-1,0} };
typedef struct
{
    int x,y;
} Point;
int a[10][10],vis[10][10];
int pre[50];
Point l[50];
int print(int t)
{
    if(pre[t]==-1)
    {
        printf("(%d, %d)\n",l[t].x,l[t].y);
        return 1;
    }
    else
    {
        if(print(pre[t]))
        {
            printf("(%d, %d)\n",l[t].x,l[t].y);
            return 1;
        }
    }
}
void bfs()
{

    int head,tail;
    int x1,x2,y1,y2;
    memset(vis,0,sizeof(vis));
    l[0].x=0,l[0].y=0;
    head=0;
    tail=1;
    pre[0]=-1;
    vis[0][0]=1;
    while(head<tail)
    {
        x1=l[head].x;
        y1=l[head].y;
        for(int i=0; i<4; i++)
        {
            x2=x1+nex[i][0];
            y2=y1+nex[i][1];
            if(x2>=0&&x2<5&&y2>=0&&y2<5&&!a[x2][y2]&&!vis[x2][y2])
            {
                pre[tail]=head;
                l[tail].x=x2,l[tail].y=y2;
                if(x2==4&&y2==4)
                {
                    print(tail);
                    return ;
                }
                tail++;
                vis[x2][y2]=1;
            }
        }
        head++;
    }
}
int main()
{
    for(int i=0; i<5; i++)
        for(int j=0; j<5; j++)
            scanf("%d",&a[i][j]);
    bfs();
    return 0;
}

 

posted @ 2017-07-19 15:11  Twsc  阅读(571)  评论(0编辑  收藏  举报