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.
publicstaticintprims(intn,List<List<Integer>>edges,intstart){Set<Integer>connected=newHashSet<>();connected.add(start);inttotalPrice=0;while(connected.size()<n){intminPrice=Integer.MAX_VALUE;List<Integer>edgeConnect=null;for(List<Integer>e:edges){intnode1=e.get(0);intnode2=e.get(1);intweight=e.get(2);if((connected.contains(node1)&&!connected.contains(node2))||(connected.contains(node2)&&!connected.contains(node1))){if(weight<minPrice){minPrice=weight;edgeConnect=e;}}}if(edgeConnect==null){// If no edge found, graph might be disconnectedreturn-1;// or handle the disconnected graph case accordingly}connected.add(edgeConnect.get(0));connected.add(edgeConnect.get(1));totalPrice+=minPrice;}returntotalPrice;}
Cookie support is required to access HackerRank
Seems like cookies are disabled on this browser, please enable them to open this website
Prim's (MST) : Special Subtree
You are viewing a single comment's thread. Return to all comments →
Java Code