kruskal.c 1.5 KB

123456789101112131415161718192021222324252627282930313233343536373839
  1. #include <igraph.h>
  2. #include <time.h>
  3. #include "io.h"
  4. #include "kruskal.h"
  5. void shuffle_edges(igraph_t *g, igraph_vector_t *eids) {
  6. long int ecount = igraph_ecount(g);
  7. igraph_vector_t pairs;
  8. igraph_vector_init(&pairs, 2*ecount);
  9. int e;
  10. for (e = 0; e < ecount; ++e) {
  11. VECTOR(pairs)[2*e] = IGRAPH_FROM(g, e);
  12. VECTOR(pairs)[2*e+1] = IGRAPH_TO(g, e);
  13. }
  14. igraph_vector_init(eids, ecount);
  15. igraph_get_eids(g, eids, &pairs, 0, 0, 1);
  16. igraph_vector_destroy(&pairs);
  17. igraph_vector_shuffle(eids);
  18. }
  19. void build_tree(igraph_t *dest_tree, igraph_t *src_graph, igraph_vector_t *src_eids) {
  20. // Transfer edges from the complete graph to the tree whenever this preserves acyclicity.
  21. // Cycles can be detected by seeing whether two vertices already have a path between them.
  22. igraph_integer_t edge, from, to;
  23. igraph_matrix_t paths;
  24. igraph_matrix_init(&paths, 1, 1);
  25. long int tree_size = igraph_vcount(src_graph) - 1;
  26. while((long int)igraph_ecount(dest_tree) < tree_size && (long int)igraph_vector_size(src_eids) > 0) {
  27. edge = igraph_vector_pop_back(src_eids);
  28. igraph_edge(src_graph, edge, &from, &to);
  29. MATRIX(paths, 0, 0) = IGRAPH_INFINITY;
  30. igraph_shortest_paths(dest_tree, &paths, igraph_vss_1(from), igraph_vss_1(to), IGRAPH_ALL);
  31. if(MATRIX(paths, 0, 0) == IGRAPH_INFINITY) {
  32. igraph_add_edge(dest_tree, from, to);
  33. }
  34. }
  35. igraph_matrix_destroy(&paths);
  36. }