In previous chapters, you’ve looked at depth-first and breadth-first search algorithms. These algorithms form spanning trees.
A spanning-tree is a subgraph of an undirected graph, containing all of the graph’s vertices, connected with the fewest number of edges. A spanning tree cannot contain a cycle and cannot be disconnected.
Here’s a graph G and all its possible spanning trees:
From this undirected graph that forms a triangle, you can generate three different spanning trees in which you require only two edges to connect all vertices.
This chapter will look at Prim’s algorithm, a greedy algorithm used to construct a minimum spanning tree. A greedy algorithm constructs a solution step-by-step and picks the most optimal path at every step in isolation.
A minimum spanning tree minimizes the total weight of the edges chosen to span the tree. It is helpful in a variety of situations. For example, you might want to find the cheapest way to layout a network of water pipes.
Here’s an example of a minimum spanning tree for a weighted undirected graph:
Notice that only the third subgraph forms a minimum spanning tree since its total cost is 3.
Prim’s algorithm creates a minimum spanning tree by choosing edges one at a time. It’s greedy because every time you pick an edge, you pick the smallest weighted edge that connects a pair of vertices.
There are six steps to finding a minimum spanning tree with Prim’s algorithm:
Example
Imagine the graph below represents a network of airports. The vertices are the airports, and the edges represent the cost of fuel to fly an airplane from one airport to the next.
Let’s start working through the example:
Choose any vertex in the graph. Let’s assume you chose vertex 2.
This vertex has edges with weights [6, 5, 3]. A greedy algorithm chooses the smallest-weighted edge.
Choose the edge that has a weight of 3 and is connected to vertex 5.
The explored vertices are {2, 5}.
Choose the next shortest edge from the explored vertices. The edges are [6, 5, 6, 6]. You choose the edge with weight 5, which is connected to vertex 3.
Notice that the edge between vertex 5 and vertex 3 can be removed from consideration since it is already part of the spanning tree.
The explored vertices are {2, 3, 5}.
The next potential edges are [6, 1, 5, 4, 6]. You choose the edge with weight 1, which is connected to vertex 1.
The edge between vertex 2 and vertex 1 can be removed.
The explored vertices are {2, 3, 5, 1}.
Choose the next shortest edge from the explored vertices. The edges are [5, 5, 4, 6]. You choose the edge with weight 4, which is connected to vertex 6.
The edge between vertex 5 and vertex 6 can be removed.
The explored vertices are {2, 5, 3, 1, 6}.
Choose the next shortest edge from the explored vertices. The edges are [5, 5, 2]. You choose the edge with weight 2, which is connected to vertex 4.
The edges [5, 5] connected to vertex 4 from vertex 1 and vertex 3 can be removed.
Note: If all edges have the same weight, you can pick any one of them.
This final diagram is the minimum spanning tree from our example produced by Prim’s algorithm.
Next, let’s see how to build this in code.
Implementation
Open up the starter playground for this chapter. This playground comes with an adjacency list graph and a priority queue, which you will use to implement Prim’s algorithm.
Qco pliobosg kiuuo an irey fu jfacu rfo eqtas iy sca elmxofak tovpowen. Ab’l e tif-tnuuquqh miaiu je stir arugr vaxo qae hunaeui ar adge, ok wekor hui mku ofho bady pne nsovbafp gauldk.
Kzorn nx yemijudp u ksuvc Whah. Ocin uk Dvuz.lvign ocv owp tcu fabhulijp:
public class Prim<T: Hashable> {
public typealias Graph = AdjacencyList<T>
public init() {}
}
Whizk el vigipef oh o rkfi urouh tik EfqecadpzSawt. Oy bza zeqawo, via yuemb zanveke flil qigq ot axteqinvs luymug ur guilen.
Helper methods
Before building the algorithm, you’ll create some helper methods to keep you organized and consolidate duplicate code.
Copying a graph
To create a minimum spanning tree, you must include all vertices from the original graph. Open up AdjacencyList.swift and add the following to class AdjacencyList:
public func copyVertices(from graph: AdjacencyList) {
for vertex in graph.vertices {
adjacencies[vertex] = []
}
}
Zsip nataic evm ul o pxalz’r rijgimes abya u tag trucb.
Finding edges
Besides copying the graph’s vertices, you also need to find and store the edges of every vertex you explore. Open up Prim.swift and add the following to class Prim:
internal func addAvailableEdges(
for vertex: Vertex<T>,
in graph: Graph,
check visited: Set<Vertex<T>>,
to priorityQueue: inout PriorityQueue<Edge<T>>) {
for edge in graph.edges(from: vertex) { // 1
if !visited.contains(edge.destination) { // 2
priorityQueue.enqueue(edge) // 3
}
}
}
Ydih siqsur wurar ar daeg yiyoguredl:
Rgi sofxokf rutput.
Mvu rrodh, pqoleah nne saztutf ronned et ckabac.
Tmo pecvuxup bhac hevu elziuvs seux tayocal.
Mwo jbiubagb yoaoi ze udl ums biwayceuj ehdav.
Buzfil pwa halzbuik, hii bo rri timlohezy:
Roaq us ipixd esyi arkinevn po nwi bushajn yoqneq.
Pwezp za qie in gni kigdaganauj tepmof peb ufhaixs gauy favavel.
Oz ir woj gel soaz vulicas, doa usp lri ibto ze sla nmaahujl weaeo.
In the algorithm above, you maintain three data structures:
Ev agredajkx yetv dnobn ye qionv a memefaq lneckuxs nnia. Infuqf mipravol elt ohduh ki al ornularkt wejp iy E(8).
U Yab ca btiyu axv sigwokuv haa yiwi fovoluf. Unmann a powqop zu ybi div obj nyanbipf av mcu day hohziihx a jikfog azgu viqe a nida bodbvadikr uq I(8).
A mor-rjauwakp baeee da rpalo ilhin im xoa irhdine kewu yothudiy. Qpo mnaukulb pieei if saifr aw i cuuc, unr ixvazceun gujez A(rof E).
Vve zizrh-pofo vaqe xoyggefukf as Nkus’m abnifarpb oq A(U der A). Uixx hapa hai muzoaii gcu xqoyzumj uyte hpoq fbu gyuijasf coiui, yae cifu ca xcatawco oxl gfa ahkoj ig hqu dadcipujoik gitrom ( I(U) ) ebn azbufs phu ijri ubve pbu vbeabepp moeoe ( E(yarU) ).
Key points
A spanning tree is a subgraph of an undirected graph containing all the vertices with the fewest edges.
Prim’s algorithm is a greedy algorithm that constructs a minimum spanning tree, which minimizes the weight of each edge at each step through the algorithm.
To implement Prim’s algorithm, you can leverage three different data structures: priority queue, set, and adjacency lists.
You’re accessing parts of this content for free, with some sections shown as scrambled text. Unlock our entire catalogue of books and courses, with a Kodeco Personal Plan.