Skip to content

One if condition is missing from Prims Efficient solution #16

Open

Description

@amantayal6797

The given solution is breaking for the following test case on gfg
10 11
0 1 7
0 4 4
0 7 8
0 9 3
1 7 7
1 8 3
2 5 8
2 7 10
3 4 3
4 6 10
5 7 8

Activity

  1. amantayal6797 commented on Jul 8, 2021

    @amantayal6797
    Author

    This is the correct code for the gfg problem

    int spanningTree(int V, vector<vector> adj[]){
    int res=0;
    vector MST(V,false);
    vector dist(V,INT_MAX);
    dist[0]=0;
    priority_queue<pair<int,int>,vector<pair<int,int>>,greater<pair<int,int>>> q;
    q.push({0,0});

    while(q.size()!=0){
    int ver;
    ver=q.top().second;
    q.pop();
    if(MST[ver]==true) //This is very important
    continue;

    MST[ver]=true;
    res+=dist[ver];

    for(int j=0;j<adj[ver].size();j++){
    int v=adj[ver][j][0];
    int wt=adj[ver][j][1];
    if(MST[v]==false && dist[v]>wt){
    dist[v] = wt;
    q.push({dist[v],v});
    }
    }
    }
    return res;
    }

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Projects

    No projects

      Milestone

      No milestone

      Relationships

      None yet

      Development

      No branches or pull requests

      Issue actions