广度优先搜索(BFS)是一种基于队列实现的搜索算法,其主要思想是从起点开始向周围扩展,先遍历所有与起点相邻的节点,再遍历与这些节点相邻的节点,以此类推,直到找到终点或者搜索全部节点为止。每次遍历到一个节点时,将该节点加入队列中,直到队列为空为止。
以下是一个基本的C++实现:
#include <iostream>
#include <queue>
using namespace std;
const int N = 100010;
int n, m;
int g[N][N]; // 存储图
bool st[N]; // 存储每个节点是否遍历过
int dist[N]; // 存储起点到每个节点的距离
void bfs(int start)
{
queue<int> q;
q.push(start);
st[start] = true;
dist[start] = 0;
while (!q.empty())
{
int t = q.front();
q.pop();
// 遍历与当前节点相邻的节点
for (int i = 1; i <= n; i ++)
{
if (g[t][i] && !st[i])
{
q.push(i);
st[i] = true;
dist[i] = dist[t] + 1;
}
}
}
}
int main()
{
scanf("%d%d", &n, &a