0

I'm trying to trace the path of a BFS algorithm in a weighted graph. It can be done easily if I only consider the vertices but in this case I need to trace the path along with the weights of their edges. I tried to use a path vector (commented in the code) so that I can iterate vertices and cost to reach them together but it keeps me showing errors. My code goes here:

#include<bits/stdc++.h>
using namespace std;

typedef long long int lli;

typedef pair<lli , lli> PII ;

void addEdge(lli u , lli v , lli wt , vector<PII>G[])
{
    G[u].push_back(PII(wt , v));
    G[v].push_back(PII(wt , u));
    return;
}

 void printPath(vector<PII>parent, int j)
{

    if (parent[j].second == j )
        return;

    printPath(parent, parent[j].second);

    cout << parent[j].second << " - wt " << parent[j].first << " - ";

}

void bfs( lli src , vector<PII>G[], int V, lli dest)
{
    bool vis[V];
    vector<PII>path;
    lli zero = 0 ;
    /* Here I tried to make every node it's own parent as it is the initial step. But it keeps         
    showing error*/
    ///    for(long long int i = 0; i < V ; i++)
    ///    {
        ///    path.insert(i , make_pair(zero , i));
    ///    }

    queue<PII>Q;
    Q.push(make_pair( zero , src));
    vis[src] = 1 ;

    while(!Q.empty())
    {
        PII v = Q.front();
        Q.pop();

        for( auto it : G[v.second])
        {
            if( vis[it.second] != 1)
            {
                vis[it.second] = 1 ;
                Q.push(it);
                ///path.insert( v.second , it);
            }
        }
    }
    printPath( path , dest);
}

int main()
{
    int V, E;
    lli u, v , wt ,  src, dest;
    cin >> V >> E;
    vector<PII>G[v];
    for (int i = 0; i < E ; i++)
    {
        cin >> u >> v >> wt;
        addEdge(u , v , wt , G);
    }
    cout<< "input the source: \n";
    cin >> src ;
    cout<< "input the destination: \n";
    cin >> dest ;
    bfs( src , G , V, dest );

    return 0;
}
  • `vectorG[v]` uses an uninitialized variable `v`, whereupon your program exhibits undefined behavior. – Igor Tandetnik Jun 28 '20 at 01:43
  • `vector::insert` takes an iterator as the first parameter, not an index. Since you are trying to add elements at the end anyway, make it `path.emplace_back(zero , i);` – Igor Tandetnik Jun 28 '20 at 01:47

0 Answers0