1. Linear Cut Scan (Without Priority Queue)
Intuition
Maintain a set inMST of vertices already included in the tree, starting with inMST = {0}. In each of the V - 1 steps, iterate through every edge (u, v, w) in the graph. Find the edge with minimal weight such that exactly one endpoint is in inMST and the other is outside inMST. Add that edge and vertex to inMST.
Algorithm
- Initialize
inMSTboolean array of size V with false, setinMST[0] = true. - Initialize
mstWeight = 0andmstEdges = []. - Repeat V - 1 times:
- Set
minW = infinity,bestU = -1, bestV = -1. - Iterate through all edges (u, v, w) in the graph:
- If (inMST[u] && !inMST[v]) or (!inMST[u] && inMST[v]):
- If
w < minW: -
minW = w,bestU = u,bestV = v. - Add
bestV(the outside node) toinMST,mstWeight += minW, record edge. - Return
mstWeightandmstEdges.
#include <iostream>#include <vector>#include <climits> struct Edge { int u, v, w;}; int primsBrute(int V, const std::vector<Edge>& edges) { std::vector<bool> inMST(V, false); inMST[0] = true; int totalWeight = 0; for (int step = 0; step < V - 1; ++step) { int minW = INT_MAX, bestU = -1, bestV = -1; for (const auto& e : edges) { if ((inMST[e.u] && !inMST[e.v]) || (!inMST[e.u] && inMST[e.v])) { if (e.w < minW) { minW = e.w; bestU = inMST[e.u] ? e.u : e.v; bestV = inMST[e.u] ? e.v : e.u; } } } inMST[bestV] = true; totalWeight += minW; } return totalWeight;} int main() { int V = 4; std::vector<Edge> edges = {{0,1,1},{1,2,2},{2,3,3},{0,3,4},{0,2,5}}; std::cout << "Brute Force Prim's: " << primsBrute(V, edges) << std::endl; return 0;}Time & Space Complexity
- Time complexity:
O(V * E) because in each of the V - 1 iterations we scan all E edges. - Space complexity:
O(V) for the inMST array and edge storage.