POJ-3984 迷宫问题(BFS找最短路径并保存)

问题:

定义一个二维数组: 

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表示可以走的路,只能横着走或竖着走,不能斜着走,要求编程序找出从左上角到右下角的最短路线。

输入:

一个5 × 5的二维数组,表示一个迷宫。数据保证有唯一解。

输出:

左上角到右下角的最短路径,格式如样例所示。

//#include <bits/stdc++.h>
#include <stdio.h>
#include <cmath>
#include <queue>
#define inf 0x3f3f3f3f
#define FRE() freopen("in.txt", "r", stdin)
#define FRO() freopen("out.txt", "w", stdout)

using namespace std;
typedef long long ll;
const int maxn = 6;
int dx[]={0,0,1,-1};
int dy[]={1,-1,0,0};
int mp[maxn][maxn];
struct Node
{
    int x,y;
    Node(int _x,int _y):x(_x),y(_y){}
    Node(){}
};
Node path[maxn][maxn];
queue<Node> que;

bool isin(int x,int y)
{
    if(x>=0 && x<5 && y>=0 && y<5)
        return true;
    return false;
}


void BFS()
{
    Node now = Node(0,0);
    que.push(now);
    mp[0][0]=1;

    while(!que.empty())
    {
        Node u = que.front();
        que.pop();
        if(u.x==4 && u.y==4) return;
        for(int i=0; i<4; i++)
        {
            int tx = u.x+dx[i];
            int ty = u.y+dy[i];
            if(isin(tx,ty) && mp[tx][ty]==0)
            {
                que.push(Node(tx,ty));
                mp[tx][ty] = 1;
                path[tx][ty] = u;
            }
        }

    }

}

void showPath(Node u)
{
    if(u.x==0 && u.y==0) printf("(%d, %d)\n",u.x,u.y);
    else
    {
        showPath(path[u.x][u.y]);
        printf("(%d, %d)\n",u.x,u.y);
    }
}

int main()
{
    for(int i=0; i<5; i++)
    {
        for(int j=0; j<5; j++)
        {
            scanf("%d",&mp[i][j]);
        }
    }

    BFS();
    showPath(Node(4,4));
    return 0;
}
/*
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)
*/

 

posted @ 2019-08-31 15:53  sykline  阅读(620)  评论(0编辑  收藏  举报