Example #1
0
void dfs_demo() {
	auto a = std::make_unique<TNode>('a');
	auto b = std::make_unique<TNode>('b');
	auto c = std::make_unique<TNode>('c');
	auto d = std::make_unique<TNode>('d');
	auto e = std::make_unique<TNode>('e');
	auto f = std::make_unique<TNode>('f');
	auto g = std::make_unique<TNode>('g');

	a->set_adjacent({b.get(), c.get()});
	b->set_adjacent({a.get(), d.get(), e.get()});
	c->set_adjacent({a.get(), f.get(), g.get()});
	d->set_adjacent({b.get()});
	e->set_adjacent({b.get(), f.get()});
	f->set_adjacent({c.get(), e.get()});
	g->set_adjacent({c.get()});


	// Trace all nodes
	auto graph =
		{a.get(), b.get(), c.get(), d.get(), e.get(), f.get(), g.get()};
	std::for_each(std::begin(graph), std::end(graph), [](auto n){
			if (!n->is_visited())
				do_dfs(n);
			});
}
Example #2
0
//==========================
//             -- d
//     -- b -- |
//		 |       -- e
// a --|          |
//     |       -- f
//     -- c -- |
//             -- g
//==========================
void do_dfs(TNode *n) {
	std::cout << "Visiting: " << n->get_data() << std::endl;
	n->visit();
	auto adj = n->adjacent();
	std::for_each(std::begin(adj), std::end(adj), [](TNode *r) {
			if (!r->is_visited())
			do_dfs(r);
			});
};
Example #3
0
static void do_dfs(node_t*n, int color)
{
    int t;
    n->tmp = color;
    halfedge_t*e = n->edges;
    while(e) {
	if(e->fwd->node->tmp<0)
	    do_dfs(e->fwd->node, color);
	e = e->next;
    }
}
Example #4
0
int graph_find_components(graph_t*g)
{
    int t;
    int count = 0;
    for(t=0;t<g->num_nodes;t++) {
	g->nodes[t].tmp = -1;
    }
    for(t=0;t<g->num_nodes;t++) {
	if(g->nodes[t].tmp<0) {
	    do_dfs(&g->nodes[t], count++);
	}
    }
    return count;
}
int main()
{
    std::vector<std::list<char>> graph(26);
    std::vector<bool> node_done(26, 0);
    char starting_node = 'a';
    populate_graph('a', 'b', graph);
    populate_graph('b', 'c', graph);
    populate_graph('c', 'd', graph);
    populate_graph('c', 'f', graph);
    populate_graph('g', 'f', graph);
    populate_graph('d', 'f', graph);
    print_graph(graph);
    //populate_graph('a', 'b', graph);
    do_dfs(starting_node, node_done, graph);
    return 0;
}
void do_dfs(char starting, std::vector<bool> &node_done, std::vector<std::list<char>> &sgraph)
{
    if(!node_done[starting - 'a'])
    {
        node_done[starting - 'a'] = 1;
        std::cout << starting << "->";
        for(auto i = sgraph[starting - 'a'].begin(); i != sgraph[starting - 'a'].end(); i++)
        {
            if(!node_done[*i - 'a'])
            {
                do_dfs(*i, node_done, sgraph);
            }
        }
    }
    return;
}