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.
classResult{/* * Complete the 'bfs' function below. * * The function is expected to return an INTEGER_ARRAY. * The function accepts following parameters: * 1. INTEGER n * 2. INTEGER m * 3. 2D_INTEGER_ARRAY edges * 4. INTEGER s */publicstaticList<Integer>bfs(intn,intm,List<List<Integer>>edges,ints){// Write your code hereif(n<1||edges==null||edges.size()<1||s<1)returnnull;// Step 1Set<Integer>[]tree=newSet[n];for(List<Integer>edge:edges){inta=edge.get(0);intb=edge.get(1);if(tree[a-1]==null){tree[a-1]=newHashSet<Integer>();}tree[a-1].add(b);if(tree[b-1]==null){tree[b-1]=newHashSet<Integer>();}tree[b-1].add(a);}// Step 2List<Integer>res=newArrayList<Integer>();// O(n) start from Sfor(inti=0;i<n-1;i++){res.add(-1);}Set<Integer>root=tree[s-1];if(root==null)returnres;Deque<Integer>queue=newLinkedList<Integer>();for(Integerr:root){queue.add(r);}intheight=1;boolean[]visited=newboolean[n];visited[s-1]=true;while(!queue.isEmpty()){Deque<Integer>queuen=newLinkedList<Integer>();while(!queue.isEmpty()){intv=queue.poll().intValue();if(!visited[v-1]){visited[v-1]=true;// update distancesif(v>s)res.set(v-2,height*6);elseres.set(v-1,height*6);if(tree[v-1]!=null){for(Integerr:tree[v-1]){queuen.add(r);}}}}queue=queuen;height++;}// return resreturnres;}}
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 →