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.
My Javascript solution that passes all test cases with explanations:
functionbfs(n,m,edges,s){letgraph={}// fill the graph with empty sets (equivalent to Python's defaultdict(set))Array(n+1).fill(null).forEach((v,i)=>graph[i]=newSet())letresult=[]// Construct graph double linked (undirected)for(let[n1,n2]ofedges){graph[n1].add(n2)graph[n2].add(n1)}// For node i = 1...n calculate distance from the start node to 'i'for(leti=1;i<=n;i++){if(i==s)continue// skip start node in the result arrayletqueue=[]// We use distances array also as visited arrayletdistances=Array(n+1).fill(null).map(_=>-1)// start distance as -1 for alldistances[s]=0// starting node has distance of 0queue.push(s)// BFS LOOP ----------------------------while(queue.length>0){letnode=queue.shift()for(letneighborofgraph[node]){if(distances[neighbor]===-1){queue.push(neighbor)// each distance is 6 more than the previous nodedistances[neighbor]=distances[node]+6if(neighbor===i){// if the target node i is reachedqueue=[]// set the queue to empty to break the outer loopbreak// no need to continue inner loop either}}}}result.push(distances[i]||-1)}returnresult}
Cookie support is required to access HackerRank
Seems like cookies are disabled on this browser, please enable them to open this website
BFS: Shortest Reach
You are viewing a single comment's thread. Return to all comments →
My Javascript solution that passes all test cases with explanations: