1. BFS 和 DFS 的区别
1.1 DFS是按枝搜索, BFS是按层搜索
1.2 DFS是用的是是栈(内隐式,先进后出,后进先出),BFS使用的是队列(先进先出,后进后出)
1.3 DFS可以找到所有的路径,BFS可以找到最短路径
2. BFS与DFS的共同点
2.1 重点考虑父亲孩子关系,即知道父亲就可以找到所有的孩子
2.2 重点考虑孩子的合法性,即重复性和是否满足约束性条件
2.3 DFS使用的必要变量 vis[ ]标记变量 , ans[ ]答案;BFS常用的变量有 vis[ ], father[ ]
3. BFS 的两种实现方式
3.1 普通数组实现 BFS
#include <iostream>
#include <vector>
using namespace std;
const int MAX_N = 100;
int head, tail; //入队时尾指针增1, 出队时头指针增1
int queue[MAX_N];
vector<vector<int>> graph; // 图的邻接表表示
vector<bool> visited; // 标记每个结点是否已被访问
void bfs(int start)
{
head=0, tail = 1; //初始化队首指针和队尾指针
queue[tail] = start; //起点入队
visited[start] = true; //标记
while (head < tail) //队列不为空
{
head++; //头指针增1,队首出队
int parent = queue[head];
if() //如果父亲是答案,输出答案
{
cout << parent << " ";
}
for (int i = 0; i < graph[parent].size(); i++) //枚举所有孩子的线索
{
int son = graph[parent][i]; //生成孩子
if (!visited[son]) //孩子的不重复
{
tail++; //尾指针增1,孩子入队
queue[tail] = son;
visited[son] = true; //标记孩子
}
}
}
}
int main()
{
// 读入图的邻接表
// ...
// 初始化visited数组
visited.resize(num_of_nodes, false);
// 从结点0开始搜索
bfs(0);
return 0;
}
3.2 用STL(queue) 实现BFS
#include <iostream>
#include <queue>
#include <vector>
using namespace std;
vector<vector<int>> graph; // 图的邻接表表示
vector<bool> visited; // 标记每个结点是否已被访问
void bfs(int start)
{
queue<int> q;
q.push(start);
visited[start] = true;
while (!q.empty())
{
int parent = q.front();
q.pop();
if( ) //如果父亲是答案,输出
{
cout << parent << " ";
}
for (int i = 0; i < graph[parent].size(); i++) //枚举所有的孩子的线索
{
int son = graph[current][i]; //生成孩子
if (!visited[son])
{
q.push(son); //孩子入队
visited[son] = true; //标记孩子
}
}
}
}
int main()
{
// 读入图的邻接表
// ...
// 初始化visited数组
visited.resize(num_of_nodes, false);
// 从结点0开始搜索
bfs(0);
return 0;
}