CodexBloom - Programming Q&A Platform

implementing Implementing the Prim's Algorithm in C++ - Incorrect Minimum Spanning Tree Results

👀 Views: 39 đŸ’Ŧ Answers: 1 📅 Created: 2025-06-09
algorithms graph-theory prim-algorithm C++

I'm working on a project and hit a roadblock. I've looked through the documentation and I'm still confused about I'm currently implementing Prim's Algorithm to find the Minimum Spanning Tree (MST) for a given graph, but I'm getting incorrect results when I test it with specific graphs. The algorithm seems to work on smaller graphs but fails on larger ones, particularly when there are multiple edges with the same weight. Here's a snippet of my implementation: ```cpp #include <iostream> #include <vector> #include <limits> using namespace std; const int INF = numeric_limits<int>::max(); vector<int> primMST(int graph[][5], int V) { vector<int> parent(V, -1); vector<int> key(V, INF); vector<bool> inMST(V, false); key[0] = 0; parent[0] = -1; for (int count = 0; count < V - 1; count++) { int minKey = INF, minIndex; for (int v = 0; v < V; v++) { if (!inMST[v] && key[v] < minKey) { minKey = key[v]; minIndex = v; } } inMST[minIndex] = true; for (int v = 0; v < V; v++) { if (graph[minIndex][v] && !inMST[v] && graph[minIndex][v] < key[v]) { parent[v] = minIndex; key[v] = graph[minIndex][v]; } } } return parent; } ``` I'm passing a 5x5 adjacency matrix to the `primMST` function, but for graphs with multiple edges of the same weight, it seems to choose edges that do not contribute to the MST, resulting in duplicate edges in my final output. When I run this with the following graph: ```cpp int main() { int graph[5][5] = { {0, 2, 0, 6, 0}, {2, 0, 3, 8, 5}, {0, 3, 0, 0, 7}, {6, 8, 0, 0, 9}, {0, 5, 7, 9, 0} }; vector<int> mst = primMST(graph, 5); for (int i = 1; i < 5; i++) { cout << "Edge: " << mst[i] << " - " << i << endl; } return 0; } ``` I receive output that includes edges that shouldn't be part of the MST, leading to a total weight that is higher than expected. I've tried debugging by printing the `key` and `parent` arrays at each iteration, but I need to seem to pinpoint the scenario. Has anyone faced a similar question, and how can I ensure that the edges selected are indeed forming a correct MST? Any insights on handling graphs with duplicate edge weights would be greatly appreciated! What am I doing wrong? I recently upgraded to C++ 3.11. I'm working on a mobile app that needs to handle this. Thanks for taking the time to read this!