### Documentation / Algorithms / Spanning-tree

# The Prim Algorithm

Prim’s algorithm is an algorithm which allows to find a minimal spanning tree in a weighted connected graph. More informations on Wikipedia.

## Example

The following example generates a graph with the Dorogovtsev-Mendes generator and then compute a spanning-tree using the Prim algorithm. The generator creates random weights for edges that will be used by the Prim algorithm.

If no weight is present, algorithm considers that all weights are set to 1.

When an edge is in the spanning tree, the algorithm will set its “ui.class” attribute to “intree”, else the attribute is set to “notintree”. According to the css stylesheet that is defined, spanning will be displayed with thick black lines while edges not in the spanning tree will be displayed with thin gray lines.

## Complexity

0(m+m^{2}log(m)), where m = |E|

## Reference

- R. C. Prim:
*Shortest connection networks and some generalizations*. In: Bell System Technical Journal, 36 (1957), pp. 1389–1401