每日一题 - 240322 - 迷宫

本文介绍了使用深度优先搜索(DFS)和广度优先搜索(BFS)算法解决迷宫问题,通过C++代码实现,强调了字典序最小的重要性。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >


  • TAG - 算法 − 【搜索 − D F S 、搜索 − B F S 】 算法 - 【搜索 - DFS、搜索- BFS】 算法【搜索DFS、搜索BFS
  • 时间复杂度 - O ( ∗ ) O(\ast) O()
//
#include <bits/stdc++.h>
using namespace std;
// #define int long long 

const string ANS = "DDDDRRURRRRRRDRRRRDDDLDDRDDDDDDDDDDDDRDDRRRURRUURRDDDDRDRRRRRRDRRURRDDDRRRRUURUUUUUUULULLUUUURRRRUULLLUUUULLUUULUURRURRURURRRDDRRRRRDDRRDDLLLDDRRDDRDDLDDDLLDDLLLDLDDDLDDRRRRRRRRRDDDDDDRR";
const int dx[] = {1, 0, 0, -1};
const int dy[] = {0, -1, 1, 0};
const int N = 55;
char g[N][N];
bool used[N][N];

int n = 2, m = 2;

struct A {
    int x, y;
    char ch;
}dad[N][N];

void bfs(int stx, int sty) {
    queue<pair<int, int> > q;
    q.push(make_pair(stx, sty));
    used[stx][sty] = 1;

    while (!q.empty()) {
        auto [x, y] = q.front();
        q.pop();

        for (int i = 0; i < 4; i++) {
            int tx = x + dx[i];
            int ty = y + dy[i];
            if (!(tx >= 1 && tx <= n && ty >= 1 && ty <= m)) continue;
            if (used[tx][ty] || g[tx][ty] == '1') continue;     // '0' 有效 
            
            // cout << x << " " << y << " - " << tx << " " << ty << endl;
            
            q.push(make_pair(tx, ty));
            dad[tx][ty] = {x, y, "DLRU"[i]};
            used[tx][ty] = 1;               // tx ty
        }
        // 要保证字典序最小 所以讲究先来后到 先来的提前给儿子打上标记
    }
}

void dfs(int x, int y) {
    if (x == 1 && y == 1) return;

    dfs(dad[x][y].x, dad[x][y].y);
    cout << dad[x][y].ch;
}

void solve() {
    for (int i = 1; i <= n; i++) {
        for (int j = 1; j <= m; j++) {
            cin >> g[i][j];
        }
    }
    bfs(1, 1);
    dfs(n, m);
}

signed main() {
    int t = 1;
    // scanf("%d", &t);
    while (t--) solve();
    return 0;
}

实现细节

  • 字典序最小

参考示意图

  • `

参考链接

  • `

作者 | 乐意奥AI

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值