BFS | 3984 | 迷宫问题

学习BFS,找到raphealguo的博客介绍BFS,完成了这题。

POJ 3984 迷宫问题

#include <cstdio>
#include <iostream>
#include <queue>
using namespace std;

int map[5][5], visit[25], path[25];                   // 
int dir[4][2] = { {-1, 0}, {1, 0}, {0, -1}, {0, 1} }; // 左下上右搜索

bool is_leagal(int x, int y)
{
    if (x < 0 || x > 4 || y < 0 || y > 4)
        return false;
    if (map[x][y] == 1)
        return false;
    return true;
}

void print(int final)
{
    if (path[final] != -1)
        print(path[final]);
    printf("(%d, %d)\n", final / 5, final % 5);
}

void dfs()
{
    queue<int> Q;
    int now, next;
    int x, y, temp_x, temp_y;


    // 第一个节点入列
    visit[0] = true;
    path[0] = -1;
    Q.push(0);    
    while (!Q.empty())
    {
        // 取出第一个节点
        now = Q.front();
        Q.pop();
        x = now / 5;
        y = now % 5;
        for (int i = 0; i < 5; ++i)
        {
            temp_x = x + dir[i][0];
            temp_y = y + dir[i][1];
            next = temp_x * 5 + temp_y;
            if (is_leagal(temp_x, temp_y) && !visit[next])
            {
                path[next] = now;
                if (next == 24) return;
                visit[next] = true;
                Q.push(next); // 把周围合法节点入列
            }
        }
    }
}

int main()
{
    for (int i = 0; i < 5; ++i)
        for (int j = 0; j < 5; ++j)
            scanf("%d", &map[i][j]);
    dfs();
    print(24);
}
可以最快的获得路径,因为BFS类似一层一层的扒皮,所以可以最快的找到一条路径。

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

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值