BFS专题7 多终点迷宫问题


BFS专题7 多终点迷宫问题

原创 于 2023-09-28 13:14:42 发布 · 粉丝可见 · 145 阅读 · 0 · 0 · 本内容遵循CC 4.0 BY-SA版权协议 版权声明:本文为博主原创文章,遵循 CC 4.0 BY-SA 版权协议,转载请附上原文出处链接和本声明。 GEO检测 · 编辑
文章链接:https://blog.csdn.net/hacker_51/article/details/133381809

题目:

样例:

cobol<br/>3 3<br/>0 0 0<br/>1 0 0<br/>0 1 0<br/>
cobol<br/>0 1 2<br/>-1 2 3<br/>-1 -1 4<br/>

思路:

单纯的 BFS 迷宫问题 ,只是标记一下每个点的 step,注意初始化答案数组都为 -1.

代码详解如下:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
#include <iostream>
#include <vector>
#include <queue>
#include <algorithm>
#include <unordered_map>
#define endl '\n'
#define x first
#define y second
#define mk make_pair
#define YES puts("YES")
#define NO puts("NO")
#define umap unordered_map
#define All(x) x.begin(),x.end()
#pragma GCC optimize(3,"Ofast","inline")
#define ___G std::ios::sync_with_stdio(false),cin.tie(0), cout.tie(0)
using namespace std;

// 坐标
using PII = pair<int,int>;

const int N = 500;

// 地图
int n,m;
int g[N][N];

// 答案步数数组
int ans[N][N];

// 标记走动的坐标
bool st[N][N];

// 控制方向坐标
int dx[4] = {1,-1,0,0};
int dy[4] = {0,0,1,-1};

// 坐标走动条件
inline bool isRun(int &x,int &y)
{
return (~x && ~y && x < n && y < m && !g[x][y] && !st[x][y]);
}

inline void BFS()
{
int step = 0;

queue<PII>q;
// 存储起点
q.push(mk(0,0));

// 开始BFS
while(q.size())
{
int sz = q.size();
while(sz--)
{
auto now = q.front();
q.pop();

// 标记答案步数数组
ans[now.x][now.y] = step;

// 标记当前走动的坐标
st[now.x][now.y] = true;

// 开始寻找走动方向的坐标
for(int i = 0;i < 4;++i)
{
int bx = now.x + dx[i];
int by = now.y + dy[i];

// 如果可以走动该方向
if(isRun(bx,by))
{
// 标记并存储
st[bx][by] = true;
q.push(mk(bx,by));
}
}
}
++step;
}
}

// 输出答案步数数组
inline void PrintAns()
{
for(int i = 0;i < n;++i)
{
for(int j = 0;j < m;++j)
{
if(j) cout << ' ';
cout << ans[i][j];
}
if(i < n) cout << endl;
}
}

inline void solve()
{
cin >> n >> m;
for(int i = 0;i < n;++i)
{
for(int j = 0;j < m;++j)
{
cin >> g[i][j];

// 答案数组初始化
ans[i][j] = -1;
}
}

// 开始BFS
BFS();

// 输出答案
PrintAns();
}


int main()
{
// freopen("a.txt", "r", stdin);
___G;
int _t = 1;
// cin >> _t;
while (_t--)
{
solve();
}

return 0;
}

最后提交:


觉得不错的话,给点打赏吧 ୧(๑•̀⌄•́๑)૭

微信二维码

wechat pay

支付宝二维码

ali pay

BFS专题7 多终点迷宫问题
http://blog.angindem.cn/2023/09/28/Angindem-CSDN博客/074_74/
作者
Angindem
发布于
2023年9月28日
许可协议