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.
Here is my Javascript solution, it passes all cases including case #5 in under 200ms.
I actually had a problem where case #5 times-out, I noticed that was because I was spliting the input and then using shift() array function to read it line by line, switching to tracked index significantly enhanced performance.
functionprocessData(input){input=input.split("\n");varq=parseInt(input.shift());vararrIdx=0;for(vari=0;i<q;i++){vararr=input[arrIdx++].split(" ").map(Number);varn=arr[0];varm=arr[1];// Build data structure, array in arrayvarnodesArr=[];for(varw=0;w<m;w++){varnode=input[arrIdx++].split(" ").map(Number);varfrom=node[0];varto=node[1];if(!nodesArr[from]){nodesArr[from]=[];}if(!nodesArr[to]){nodesArr[to]=[];}if(from>n||to>n){continue;}nodesArr[from].push(to);nodesArr[to].push(from);}varroot=parseInt(input[arrIdx++]);// Process graph using BFSvarpassedOver=[];processGraph(nodesArr,root,passedOver);// Print resultsvarres=[];for(varj=1;j<=n;j++){if(j==root){continue;}if(!passedOver[j]){res.push(-1);continue;}res.push(passedOver[j]);}console.log(res.join(" "));}}functionprocessGraph(nodesArr,root,passedOver){varqueue=[];queue.push(root);passedOver[root]=0;while(queue.length>0){varnodeIdx=queue.shift();varnodeConnections=nodesArr[nodeIdx];if(!nodeConnections){continue;}vardistanceFromRoot=passedOver[nodeIdx];for(vari=0;i<nodeConnections.length;i++){varconnIdx=nodeConnections[i];if(passedOver[connIdx]){continue;}passedOver[connIdx]=distanceFromRoot+6;queue.push(connIdx);}}}
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 in a Graph
You are viewing a single comment's thread. Return to all comments →
Here is my Javascript solution, it passes all cases including case #5 in under 200ms.
I actually had a problem where case #5 times-out, I noticed that was because I was spliting the input and then using shift() array function to read it line by line, switching to tracked index significantly enhanced performance.