poj3984迷宫问题BFS

迷宫问题
Time Limit: 1000MS Memory Limit: 65536K
Total Submissions: 28524 Accepted: 16440

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+记录路径
#include<iostream>
using namespace std;
int mapp[5][5];
//相邻四个节点
int borderUponX[4] = {0, 0, 1, -1};
int borderUponY[4] = {1, -1, 0, 0};
int frontt = 0, rear = 1;
struct node
{
    int pre;
    int x;
    int y;
} path[100];
void print(int i)
{
    if (path[i].pre != -1)
    {
        print(path[i].pre);
        cout << "(" << path[i].x << ", " << path[i].y << ")" << endl;
    }
    else
        cout << "(" << path[i].x << ", " << path[i].y << ")" << endl;
}
void bfs(int x, int y)
{
    //开始节点(出发),前面没有节点了
    path[frontt].x = x;
    path[frontt].y = y;
    path[frontt].pre = -1;
    //当front == rear的时候说明已经走完了所有“相邻”节点且都不通
    while (frontt < rear)
    {
        for (int i = 0; i != 4; i++)
        {
            //相邻节点坐标
            int pathX = path[frontt].x + borderUponX[i];
            int pathY = path[frontt].y + borderUponY[i];
            //不符合的节点(遇到边界或已经走过了)
            if (pathY < 0 || pathX < 0 || pathX > 4 || pathY > 4 || mapp[pathX][pathY])
                continue;
            else
            {//将front的相邻的可以过去的并且是还没有走过的节点加到路径里面
                mapp[pathX][pathY] = 1;
                path[rear].x = pathX;
                path[rear].y = pathY;
                path[rear].pre = frontt;
                rear++;
            }
            if (pathX == 4 && pathY == 4)
            {
                print(rear - 1);
                break;
            }
        }
        frontt++;
    }
}

int main()
{
    for(int i = 0;i < 5;i++)
      for(int j = 0;j < 5;j++)
        cin >> mapp[i][j];
    bfs(0,0);
    return 0;
}


  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值