我是新手,可以制作一个简单的图形来执行深度优先搜索。这是我创建的图形。
我从节点1开始执行深度优先搜索。然后我打印出每个节点的发现和完成时间,其中节点0的时间为-1,因为它从未到达过。如果两个或更多节点具有相同的下一次访问条件,我想选择索引最小的节点。
因此,我想要的输出是:
Discover Times: -1 0 1 3
Finish Times: -1 5 2 4
当我插入这样的边缘时,一切都很好
boost::add_edge(boost::vertex(1, graph1), boost::vertex(2, graph1), graph1);
boost::add_edge(boost::vertex(1, graph1), boost::vertex(3, graph1), graph1);
但是当我以相反的顺序添加边缘时
boost::add_edge(boost::vertex(1, graph2), boost::vertex(3, graph2), graph2);
boost::add_edge(boost::vertex(1, graph2), boost::vertex(2, graph2), graph2);
输出为
Discover Times: -1 0 3 1
Finish Times: -1 5 4 2
这意味着节点3在节点2之前被访问。
我怀疑我可以利用boost::vertex_index
来强制执行访问命令。另外,我仍然对boost::make_iterator_property_map(&color_map[0], boost::get(boost::vertex_index, graph), color_map[0])
如何影响我的深度优先搜索感到困惑。
我的整个代码在这里:
#include <boost/graph/adjacency_list.hpp>
#include <boost/graph/depth_first_search.hpp>
#include <boost/graph/visitors.hpp>
#include <iostream>
typedef boost::adjacency_list<boost::listS, boost::vecS, boost::directedS> graph_t;
void print_vector(std::vector<int> vec) {
for(std::vector<int>::const_iterator i = vec.begin(); i != vec.end(); ++i) {
std::cout << *i << ' ';
}
std::cout << std::endl;
}
void dfs(graph_t graph, int start_node) {
int num_nodes = boost::num_vertices(graph);
std::vector<int> dtime(num_nodes, -1);
std::vector<int> ftime(num_nodes, -1);
std::vector<boost::default_color_type> color_map(num_nodes);
int time = -1;
boost::depth_first_visit(
graph,
boost::vertex(start_node, graph),
boost::make_dfs_visitor(std::make_pair(
boost::stamp_times(&dtime[0], time, boost::on_discover_vertex()),
boost::stamp_times(&ftime[0], time, boost::on_finish_vertex())
)),
boost::make_iterator_property_map(&color_map[0], boost::get(boost::vertex_index, graph), color_map[0])
);
std::cout << "Discover Times: ";
print_vector(dtime);
std::cout << "Finish Times: ";
print_vector(ftime);
}
int main() {
std::ios_base::sync_with_stdio(false);
int start_node = 1;
int num_nodes = 4;
graph_t graph1(num_nodes), graph2(num_nodes);
// Add edges in order 1
boost::add_edge(boost::vertex(1, graph1), boost::vertex(2, graph1), graph1);
boost::add_edge(boost::vertex(1, graph1), boost::vertex(3, graph1), graph1);
// Add edges in order 2
boost::add_edge(boost::vertex(1, graph2), boost::vertex(3, graph2), graph2);
boost::add_edge(boost::vertex(1, graph2), boost::vertex(2, graph2), graph2);
std::cout << std::endl << "GRAPH 1" << std::endl;
dfs(graph1, start_node);
std::cout << std::endl << "GRAPH 2" << std::endl;
dfs(graph2, start_node);
}
哪个给出输出:
GRAPH 1
Discover Times: -1 0 1 3
Finish Times: -1 5 2 4
GRAPH 2
Discover Times: -1 0 3 1
Finish Times: -1 5 4 2
任何帮助表示感谢,谢谢。