(graph)
| 13 | }; |
| 14 | |
| 15 | const prim = (graph) => { |
| 16 | const parent = []; // Stores the MST |
| 17 | const key = []; // Keeps track of the minimum edge weights |
| 18 | const visited = []; // Marks visited vertices |
| 19 | const { length } = graph; |
| 20 | |
| 21 | // Initialize all key values as infinite and visited as false |
| 22 | for (let i = 0; i < length; i++) { |
| 23 | key[i] = INF; |
| 24 | visited[i] = false; |
| 25 | } |
| 26 | |
| 27 | key[0] = 0; // Start with the first vertex |
| 28 | parent[0] = -1; // The first vertex is the root of the MST |
| 29 | |
| 30 | // Find the MST for all vertices |
| 31 | for (let i = 0; i < length - 1; i++) { |
| 32 | const u = minKey(graph, key, visited); // Select the vertex with the minimum key value |
| 33 | visited[u] = true; // Mark the selected vertex as visited |
| 34 | |
| 35 | // Update key values and parent for adjacent vertices |
| 36 | for (let v = 0; v < length; v++) { |
| 37 | if (graph[u][v] && !visited[v] && graph[u][v] < key[v]) { |
| 38 | parent[v] = u; // Update parent to store the edge in the MST |
| 39 | key[v] = graph[u][v]; // Update key value to the minimum edge weight |
| 40 | } |
| 41 | } |
| 42 | } |
| 43 | |
| 44 | return parent; // Return the MST |
| 45 | }; |
| 46 | |
| 47 | module.exports = prim; |
no test coverage detected