c++广度优先搜索
c++算法
·
比如,在上面这个简单的有向图上面实现从某个节点开始的广度优先搜索。完整代码在最下方第5小节。
1. 首先建图
struct SimpleGraph {
std::unordered_map<char, std::vector<char>> edges;
std::vector<char> neighbors(char id) {
return edges[id];
}
};
SimpleGraph example_graph{ {
{'A',{'B'}},
{'B',{'C'}},
{'C',{'B','D','F'}},
{'D',{'C','E'}},
{'E',{'F'}},
{'F',{}},
} };
2. 广度优先搜索
void breadth_first_search(SimpleGraph graph, char start) {
std::queue<char> frontier;
frontier.push(start);
std::unordered_set<char> reached;
reached.insert(start);
while (!frontier.empty()) {
char current = frontier.front();
frontier.pop();
std::cout << "visiting " << current << std::endl;
for (char next : graph.neighbors(current)) {
if (reached.find(next) == reached.end()) {
// 说明该点没有被访问过
// 则加入队列,以后要访问它的邻居
frontier.push(next);
// 该点已被访问
reached.insert(next);
}
}
}
}
3. 测试
std::cout << "reachable from A: " << std::endl;
breadth_first_search(example_graph, 'A');
std::cout << "reachable from E: " << std::endl;
breadth_first_search(example_graph, 'E');
4. 结果
5. 完整代码
#include<iostream>
#include<unordered_map>
#include<vector>
#include<queue>
#include<unordered_set>
struct SimpleGraph {
std::unordered_map<char, std::vector<char>> edges;
std::vector<char> neighbors(char id) {
return edges[id];
}
};
SimpleGraph example_graph{ {
{'A',{'B'}},
{'B',{'C'}},
{'C',{'B','D','F'}},
{'D',{'C','E'}},
{'E',{'F'}},
{'F',{}},
} };
void breadth_first_search(SimpleGraph graph, char start) {
std::queue<char> frontier;
frontier.push(start);
std::unordered_set<char> reached;
reached.insert(start);
while (!frontier.empty()) {
char current = frontier.front();
frontier.pop();
std::cout << "visiting " << current << std::endl;
for (char next : graph.neighbors(current)) {
if (reached.find(next) == reached.end()) {
// 说明该点没有被访问过
// 则加入队列,以后要访问它的邻居
frontier.push(next);
// 该点已被访问
reached.insert(next);
}
}
}
}
int main()
{
std::cout << "reachable from A: " << std::endl;
breadth_first_search(example_graph, 'A');
std::cout << "reachable from E: " << std::endl;
breadth_first_search(example_graph, 'E');
return 0;
}
更多推荐
已为社区贡献15条内容
所有评论(0)