I'm doing a graph question and here I'm using BFS. I know bfs gives us the shortest path from a given node to all the other node in an array but I also want to store the nodes included in those shortest path. How can I achieve this-
Here's a piece of my code-
void bfsUtil(ll src, ll *pred, ll *dist, bool *visited){
queue<ll> q;
visited[src]=true;
dist[src]=0;
q.push(src);
// an array of vector to store the path between a given node to all the other node.
vector<ll> path[V+1];
for(int i=0; i<=V; i++){
// pushed back source first in every path as source node will definitely going to be there.
path[i].push_back(src);
}
while (!q.empty())
{
ll u = q.front();
q.pop();
for(ll i=0; i<adj[u].size(); i++){
if(!visited[adj[u][i]]){
visited[adj[u][i]]=true;
dist[adj[u][i]]=dist[u]+1;
pred[adj[u][i]]=u;
q.push(adj[u][i]);
// pushing the node and its parent-
path[adj[u][i]].push_back(u);
path[adj[u][i]].push_back(adj[u][i]);
}
}
}
for(int i=0; i<=V; i++){
for(int j=0; j<path[i].size(); j++) cout << path[i][j] << " ";
cout << "\n";
}
}
The output is not accurate, i know I'm not pushing nodes correctly, but how can I do this? Any help would be appreciated.