We use cookies to ensure you have the best browsing experience on our website. Please read our cookie policy for more information about how we use cookies.
vector<int>bfs(intn,intm,vector<vector<int>>edges,ints){inti,weight=6;intvisited[n];intsv,ev;vector<int>distance(n);// Store the distances to all nodes from start node, including start nodequeue<int>q;q.push(s);for(i=0;i<n;++i){visited[i]=distance[i]=0;}while(!q.empty()){intw=q.front();q.pop();if(!visited[w-1])visited[w-1]=1;// Search for edges that connect current nodefor(i=0;i<edges.size();++i){sv=edges[i][0];ev=edges[i][1];// The distance to the other node from start node is the distance to the current node from start node + weightif(sv==w){if(!visited[ev-1]){visited[ev-1]=1;q.push(ev);distance[ev-1]+=distance[sv-1]+weight;}}elseif(ev==w){if(!visited[sv-1]){visited[sv-1]=1;q.push(sv);distance[sv-1]+=distance[ev-1]+weight;}}}}// Delete the start node from distance tabledistance.erase(distance.begin()+(s-1));// If the distance from start node to a node is 0, then there is no connection between the two. for(intn=0;n<distance.size();++n){if(distance[n]==0)distance[n]=-1;}returndistance;}
Cookie support is required to access HackerRank
Seems like cookies are disabled on this browser, please enable them to open this website
Breadth First Search: Shortest Reach
You are viewing a single comment's thread. Return to all comments →