能解决什么问题
走迷宫问题
找连通块
代码
#include <queue>
#include <cstring>
typedef pair<int, int> PII;
int n, m;
PII start;
int g[N][N];
int dist[N][N];
int dx[] = {0, 0, 1, -1}, dy[] = {1, -1, 0, 0};
void bfs()
{
memset(dist, -1, sizeof dist);
queue<PII> q;
q.push(start);
dist[start.first][start.second] = 0;
while (!q.empty()) {
PII t = q.front();
q.pop();
if (到达终点) {
printf("%d", dist[t.first][t.second]);
return;
}
for (int i = 0; i < 4; i++) {
int x = t.first + dx[i], y = t.second + dy[i];
if (x >= 0 && x < n && y >= 0 && y < m && dist[x][y] == -1 && 可以走到 g[x][y]) {
q.push({x, y});
dist[x][y] = dist[t.first][t.second] + 1;
}
}
}
return; // 表明走不到终点
}