@Param
$G(V, E, W)$, a weighted, undirected graph
@Returns
$F$, A subgraph of $G$ that contains all vertices of $G$ and minimizes the sum of its weights:
$$ \sum_ {e\in F.\texttt{Edges}}W(e) $$
where $W:E \to \R$ is the weight function.
An undirected edge $uv$ from $G\backslash F$ is safe with respect to intermediate spanning tree $F$ if
This is the edge that’s **crossing the cut** and the greedy choice for Prim’s and Kruskal’s.
@Hint
If both $u$ and $v$ are in $F$, then we get a cycle. If neither are in $F$, then $uv$ is not connected to $F$
function GenericMST(G: Graph) -> Set<Edges>:
F = {} // empty tree or empty set
while F is not a spanning tree:
add a safe edge to F
return F
We just need to fill in the details for:
Both Prim’s and Kruskal’s MST have a nice 1 liner describing the entire algorithm.
Prim: Keep adding minimum weight safe edges to $F$
Kruskal: Scan the edges by increasing weight. If the current edge is safe, add it to $F$