C++ Boost

prim_minimum_spanning_tree

Graphs: undirected
Properties: distance, weight, color, vertex id
Complexity: O(E log V)

(1)
template <class VertexListGraph, class Vertex>
void prim_minimum_spanning_tree(VertexListGraph& G, Vertex s);

(2)
template <class VertexListGraph, class Vertex, class Distance>
void prim_minimum_spanning_tree(VertexListGraph& G, Vertex s, Distance d);

(3)
template <class VertexListGraph, class Vertex,
          class Distance, class Visitor>
void prim_minimum_spanning_tree(VertexListGraph& G, Vertex s, 
                                Distance d, Visitor visit);

(4)
template <class VertexListGraph, class Vertex, class Visitor, 
          class Distance, class Weight, class Color, class ID>
void prim_minimum_spanning_tree(VertexListGraph& G, Vertex s, 
                                Distance d, Weight w, Color c, ID id,
                                Visitor visit);

This is Prim's algorithm [25,8,27,15] for solving the minimum spanning tree problem for an undirected graph with weighted edges. See Section Minimum Spanning Tree Algorithms for a definition of the minimum spanning tree problem. The implementation is simply a call to uniform_cost_search() with the appropriate choice of comparison and combine functors.

Where Defined

boost/graph/prim_minimum_spanning_tree.hpp

Requirements on Types

Complexity

The time complexity is O(E log V).

Example

The source code for this example is in examples/prim.cpp.

  typedef adjacency_list < vecS, vecS, undirectedS, 
          distance_property<>, weight_property<int> > Graph;
  typedef std::pair<int,int> E;
  const int num_nodes = 5;
  E edges[] = { E(0,2), 
                E(1,1), E(1,3), E(1,4),
                E(2,1), E(2,3),
                E(3,4),
                E(4,0) };
  int weights[] = { 1, 2, 1, 2, 7, 3, 1, 1};
  Graph G(num_nodes, edges, edges + sizeof(edges)/sizeof(E), weights);

  std::vector<Graph::vertex_descriptor> p(num_vertices(G));
  prim_minimum_spanning_tree(G, *(vertices(G).first),
                             visit_predecessor_ptr(p.begin()));

  for ( std::vector<Graph::vertex_descriptor>::iterator i = p.begin();
        i != p.end(); ++i)
    if (*i != Graph::vertex_descriptor() ) 
      cout << "parent[" << i - p.begin() 
           << "] = " << id_property_map()[*i] << endl;
    else
      cout << "parent[" << i - p.begin() << "] = no parent" << endl;
The output is:
  parent[0] = 0
  parent[1] = 3
  parent[2] = 0
  parent[3] = 4
  parent[4] = 0


Copyright © 2000 Jeremy Siek, Univ.of Notre Dame (jsiek@lsc.nd.edu)