先贴个题目:
以及原题链接: 1101. 献给阿尔吉侬的花束 - AcWing题库https://www.acwing.com/problem/content/1103/
一道很经典很裸的bfs模板题,简单提一句bfs是啥吧,感觉大家应该都知道,bfs(广度优先搜索)指从根节点开始,每次扩展遍历从当前节点能往前走一步就到达的节点(且没被走过),从而遍历整个图,实现的话一般是用队列实现的。如果不了解的话可以单独去搜搜bfs是啥,这里不过多赘述。
代码如下:
#include <iostream>
#include <queue>
#include <cstring>
#include <algorithm>
#define x first
#define y second
using namespace std;
typedef pair<int, int> PII;
const int N = 210;
int r, c;
int dx[4] = {0, 0, 1, -1}, dy[4] = {-1, 1, 0, 0};
int dis[N][N];
char map[N][N];
int bfs(PII start, PII end)
{
queue<PII> q;
q.push(start);
dis[start.x][start.y] = 0;
while (q.size())
{
PII tmp = q.front();
q.pop();
if (tmp == end)
{
return dis[end.x][end.y];
}
for (int i = 0; i < 4; ++i)
{
int tx = tmp.x + dx[i], ty = tmp.y + dy[i];
if (tx < 0 || tx >= r || ty < 0 || ty >= c)
continue;
if (map[tx][ty]!='#' && dis[tx][ty] == -1)
{
dis[tx][ty] = dis[tmp.x][tmp.y] + 1;
q.push(make_pair(tx, ty));
}
}
}
return -1;
}
int main()
{
int t;
cin >> t;
PII start, end;
while (t--)
{
memset(dis, -1, sizeof(dis));
cin >> r >> c;
for (int i = 0; i < r; ++i)
{
getchar();
for (int j = 0; j < c; ++j)
{
scanf("%c", &map[i][j]);
if (map[i][j] == 'S')
{
start = make_pair(i, j);
}
else if (map[i][j] == 'E')
{
end = make_pair(i, j);
}
}
}
int ans = bfs(start, end);
if (ans == -1)
cout << "oop!" << endl;
else
cout << ans << endl;
}
}
挺裸的板子题,做的挺爽的,一遍就ac了。
by————2024.3.16刷题记录