poj3984

http://poj.org/problem?id=3984

以前做过求路径长度的题,d[  now ]=d[ from ]+1;;

now   我们 要求路径,根据 距离的启示,我们把  now的坐标 和 from 的坐标联系起来;

因此 ,我们 用到结构体, mp[tot ] .x = x,   mp[   tot  ].y=  y,  mp[  tot] . next  =now .self ;   mp[  tot ] .self   =tot;


迷宫问题
Time Limit: 1000MS   Memory Limit: 65536K
Total Submissions: 11797   Accepted: 7067

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)

#include <iostream>
#include <queue>
#include <stdio.h>
using namespace std;
struct node
{
    int x,y,next,self;
}mp[100];
int tmp[10][10];
int dx[4]={0,1,0,-1};
int dy[4]={-1,0,1,0};
void printf(node p)
{
    if(p.next!=-1)
    printf(mp[p.next]);///回溯
    cout<<"("<<p.x<<", "<<p.y<<")"<<endl;

}
void  bfs(int x,int y)
{
    queue<node>que;
    int tot=1;
    int fon=0;
    mp[0].x=x;
    mp[0].y=y;
    mp[0].next=-1;
    mp[0].self=0;///self  表示mp  的下标
    que.push(mp[0]);
    while(!que.empty())
    {
       node now=que.front();
        que.pop();
        for(int i=0;i<4;i++)
        {
            int nx=now.x+dx[i];
            int ny=now.y+dy[i];
            if(nx>=0&&nx<=4&&ny>=0&&ny<=4&&tmp[nx][ny]==0)
            {

                tmp[nx][ny]=1;
                mp[tot].x=nx;
                mp[tot].y=ny;
                mp[tot].next=now.self;///next  =  now 的下标
                mp[tot].self=tot;/// self  = tot  自身下标
                que.push(mp[tot]);
                tot++;
            }
            if(nx==4&&ny==4)
            {
                 printf(mp[tot-1]);///tot 不存在的,要减一
               goto endW;
            }
        }
    }
    endW:;
    return;
}
int main()
{
    while(cin>>tmp[0][0])
    {
        for(int j=1;j<5;j++)
        cin>>tmp[0][j];
        for(int i=1;i<5;i++)
            for(int j=0;j<5;j++)
            cin>>tmp[i][j];
        bfs(0,0);

    }
    return 0;
}


你可能感兴趣的:(poj3984)