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 solution is written in typescript... I will appreciate any help, to improve my code
Test case passed (0,1,3,7)
My solution succeeds to pass test cases 0, 1, 3, and 7... how ever when comparing manually the output obtained for test case 6 I have the same results, but some how my answer seems to be wrong
My code is a follows
functionbfs(n: number,m: number,edges: number[][],s: number):number[]{// Creating a table of visited// each level represent a tree depth// placing the root node at depth 0letvisited: number[][]=[[s]];letpos1: number[]=[];// stack of visited nodesfor(leti=0;i<visited.length;i++){letnset=newSet<number>();// set of nodes of a given levelfor(letj=0;j<edges.length;j++){letstart=edges[j][0];// node uletnode=edges[j][1];// node v// if node v is connected to a node at an upper level through u// then add node v// if instead node u is connected to a node at an upper level through v// then add node uif(visited[i].includes(start)&&!pos1.includes(node)){nset.add(node);pos1.push(node);edges.splice(j,1);j--;}elseif(visited[i].includes(node)&&!pos1.includes(start)){nset.add(start);pos1.push(start);edges.splice(j,1);j--;}}// at the end of each level check, add the set of node to the visited stack if it has itemsif(nset.size>0){visited.push(Array.from<number>(nset));}}// creating an array of the visited nodesletres2=newSet(visited.flat().sort((a,b)=>a-b));// crating a response array filled with default values (-1)letres3: number[]=newArray(n).fill(-1);// inserting the visited elements in the respons array for checkupres2.forEach((e)=>{res3[e-1]=e;});// array to keep track of the checked positionsletpos: number[]=[];res3.splice(res3.indexOf(s),1);for(leti=1;i<visited.length;i++){for(letj=0;j<visited[i].length;j++){//if an element is found in the respons array // and has not yet been checked, calculat its distance// according to its level in the visited tableletindex=res3.indexOf(visited[i][j]);if(!pos.includes(index)&&index!==-1){res3[index]=i*6;//mark position as checkedpos.push(index);}}}returnres3;}
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 →
Need help
Language Typescript
My solution is written in typescript... I will appreciate any help, to improve my code
Test case passed (0,1,3,7)
My solution succeeds to pass test cases 0, 1, 3, and 7... how ever when comparing manually the output obtained for test case 6 I have the same results, but some how my answer seems to be wrong
My code is a follows