Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
19 changes: 17 additions & 2 deletions package-lock.json

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

96 changes: 96 additions & 0 deletions src/algorithms/graph/prim.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,96 @@
// src/algorithms/graph/prim.js

// Build adjacency list from list of edges
function buildAdjacency(edges, n) {
const adj = Array.from({ length: n }, () => []);
for (const e of edges) {
const u = e.from - 1;
const v = e.to - 1;
const w = e.weight;

adj[u].push({ u, v, w });
adj[v].push({ u: v, v: u, w }); // undirected graph
}
return adj;
}

/**
* Prim's Algorithm – Step Generator
* Yields one step at a time:
* type: "consider" | "add" | "skip" | "done"
* edge: {from, to, weight}
* visited: boolean[]
* frontier: edge[]
* mst: collected MST edges
*/
export function* primSteps(edges, nodeCount, startNode = 1) {
if (nodeCount === 0) {
yield { type: "done", mst: [], visited: [], frontier: [] };
return;
}

const adj = buildAdjacency(edges, nodeCount);
const visited = Array(nodeCount).fill(false);
const mst = [];
const frontier = [];

const pushEdges = (u) => {
for (const { v, w } of adj[u]) {
if (!visited[v]) {
frontier.push({ from: u + 1, to: v + 1, weight: w });
}
}
};

const startIdx = Math.max(1, Math.min(startNode, nodeCount)) - 1;
visited[startIdx] = true;
pushEdges(startIdx);

while (mst.length < nodeCount - 1 && frontier.length > 0) {
frontier.sort((a, b) => a.weight - b.weight);
const edge = frontier.shift();

yield {
type: "consider",
edge,
visited: [...visited],
frontier: [...frontier],
mst: [...mst],
};

const u = edge.from - 1;
const v = edge.to - 1;

if (visited[u] && visited[v]) {
yield {
type: "skip",
edge,
visited: [...visited],
frontier: [...frontier],
mst: [...mst],
};
continue;
}

const nextNode = visited[u] ? v : u;
visited[nextNode] = true;

mst.push(edge);
pushEdges(nextNode);

yield {
type: "add",
edge,
visited: [...visited],
frontier: [...frontier],
mst: [...mst],
};
}

yield {
type: "done",
mst: [...mst],
visited: [...visited],
frontier: [...frontier],
};
}
Loading
Loading