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