C++ EXC_BAD_ACCESS Error in Prim's Algorithm Implementation

51 views Asked by At

I am working on implementing Prim's algorithm in C++ to find the Minimum Spanning Tree (MST). However, I've encountered a persistent "EXC_BAD_ACCESS" error that occurs at the line key[src] = 0;.

The code reads input from a text file, e.g., "example.txt." Each line of the file begins with a vertex number. Following the vertex number are pairs of numbers, xij is the jth neighbor of vertex i (vertex labels are 0 through n), and wij is the weight of that edge.

0 x01 w01 x02 w02 x03 w03...
1 x11 w11 x12 w12 x13 w13 ...
n xn1 wn1 xn2 wn2 xn3 wn3 ...
#include <iostream>
#include <fstream>
#include <vector>
#include <list>
#include <queue>
#include <utility>
#include <limits>

using namespace std;

// iPair ==> Integer Pair
typedef pair<int, double> iPair;  // Changed to support double weights

// This class represents a weighted graph using adjacency list representation
class Graph {
    int V;  // Number of vertices

    // In a weighted graph, we need to store vertex and weight pair for every edge
    list<pair<int, double>> *adj;

public:
    Graph(int V);  // Constructor

    // Function to add an edge to the graph
    void addEdge(int u, int v, double w);  // Changed to support double weights

    // Print MST using Prim's algorithm
    void primMST();
};

// Allocates memory for the adjacency list
Graph::Graph(int V) {
    this->V = V;
    adj = new list<iPair>[V];
}

void Graph::addEdge(int u, int v, double w) {  // Changed to support double weights
    adj[u].push_back(make_pair(v, w));
    adj[v].push_back(make_pair(u, w));
}

void Graph::primMST() {
    // Create a priority queue to store vertices that
    // are being primMST. This is a min-heap.
    priority_queue<iPair, vector<iPair>, greater<iPair>> pq;

    int src = 0;  // Taking vertex 0 as source

    // Create a vector for keys and initialize all keys as infinite
    vector<double> key(V, numeric_limits<double>::max());

    // To store parent array which in turn stores MST
    vector<int> parent(V, -1);

    // To keep track of vertices included in MST
    vector<bool> inMST(V, false);

    // Insert source itself into the priority queue and initialize its key as 0.
    pq.push(make_pair(0, src));
    key[src] = 0;

    // Loop until the priority queue becomes empty
    while (!pq.empty()) {
        int u = pq.top().second;
        pq.pop();

        // Ignore vertices that have already been included in MST
        if (inMST[u]) {
            continue;
        }

        inMST[u] = true;  // Include vertex in MST

        // Iterate over all adjacent vertices
        for (auto i = adj[u].begin(); i != adj[u].end(); ++i) {
            int v = (*i).first;
            double weight = (*i).second;

            if (!inMST[v] && key[v] > weight) {
                // Update key of v
                key[v] = weight;
                pq.push(make_pair(key[v], v));
                parent[v] = u;
            }
        }
    }

    // Print MST in the format you specified
    for (int i = 0; i < V; ++i) {
        cout << i << " ";
        for (auto it = adj[i].begin(); it != adj[i].end(); ++it) {
            int v = it->first;
            double weight = it->second;
            if (v == parent[i]) {
                cout << v << " " << weight << " ";
            }
        }
        cout << endl;
    }
}

int main() {
    ifstream inputFile("example.txt");
    if (!inputFile) {
        cerr << "Failed to open the input file." << endl;
        return 1;
    }

    int V; // Number of vertices
    inputFile >> V;

    Graph g(V);

    int vertex, neighborCount;
    double weight;
    for (int i = 0; i < V; ++i) {
        inputFile >> vertex >> neighborCount;
        for (int j = 0; j < neighborCount; ++j) {
            inputFile >> vertex >> weight;
            g.addEdge(i, vertex, weight);
        }
    }

    g.primMST();

    inputFile.close();

    return 0;
}

The input:

0 1 8.0 2 5.0

1 0 8.0 2 4.0 3 6.0 4 3.0

2 0 5.0 1 4.0 4 2.0

3 1 6.0 4 5.0 5 1.0

4 1 3.0 2 2.0 3 5.0 5 4.0

5 3 1.0 4 4.0

output should be

0 2 5.0

1 4 3.0

2 0 5.0 4 2.0

3 5 1.0

4 1 3.0 2 2.0 5 4.0

5 3 1.0 4 4.0
0

There are 0 answers