您的位置:首页 > 其它

POJ 3984 BFS 打印路径

2015-07-17 15:09 288 查看
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)



BFS打印路径就是记录父亲结点,然后从后往前找出路径。再反过来输出一遍。






[code]
#include <iostream>
#include <algorithm>
#include <string.h>
#include <queue>
#include <map>
#define ll long long
#include<cstdio>
using namespace std;

int m[9][9];
int ans[30];
int dis [4][2] = {{0,1},{0,-1},{1,0},{-1,0}};
int fa[9][9];

struct node
{
    int x,y;
};
queue<node> q;
int flag=0;
int bfs( node start )
{
    fa[0][0] = 0;
    q.push(start);
    while(!q.empty())
    {
        node tmp = q.front();
        q.pop();
        for(int i = 0;i < 4;i ++)
        {
            int xx = tmp.x + dis[i][0];
            int yy = tmp.y + dis[i][1];

            if(xx>=0&&xx<5&&yy>=0&&yy<5&&!m[xx][yy])
            {
                m[xx][yy] = 1;
                node next;
                next.x = xx;
                next.y = yy;
                fa[xx][yy] = tmp.x * 10 + tmp.y;
                q.push(next);
            }
            if(xx==4&&yy==4)
            {
                flag=1;
                fa[xx][yy] = tmp.x * 10 + tmp.y;

                break;
            }
        }
        if(flag)
            break;
    }
    return 0;
}
int main()
{
    for(int i=0;i<5;i++)
    {
        for(int j=0;j<5;j++)
            cin>>m[i][j];
    }
    node ddd;
    ddd.x = 0 , ddd.y = 0 ;
    bfs(ddd);
    int cnt = 0;
    int ans[111];
    int dx = 4, dy = 4;
    int ddx,ddy;
    while(dx!=0||dy!=0)
    {
        ans[cnt++] = dx*10 + dy;

        ddx = fa[dx][dy]/10;    //这个地方注意不要改变dx的值,否则fa[dx][dy]的值会变
        ddy = fa[dx][dy]%10;

        dx=ddx,dy=ddy;
    }
    printf("(%d, %d)\n",0,0);
    for(int i=cnt - 1;i>=0;i--)
    {
        printf("(%d, %d)\n",ans[i]/10,ans[i]%10);
    }
    return 0;
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: