Prim's (MST) : Special Subtree

Sort by

recency

|

12 Discussions

|

  • + 0 comments

    Java Code

     public static int prims(int n, List<List<Integer>> edges, int start) {
             Set<Integer> connected = new HashSet<>();
            connected.add(start);
            int totalPrice = 0;
            while (connected.size() < n) {
                int minPrice = Integer.MAX_VALUE;
                List<Integer> edgeConnect = null;
                
                for (List<Integer> e : edges) {
                    int node1 = e.get(0);
                    int node2 = e.get(1);
                    int weight = 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 disconnected
                    return -1; // or handle the disconnected graph case accordingly
                }
                
                connected.add(edgeConnect.get(0));
                connected.add(edgeConnect.get(1));
                totalPrice += minPrice;   
        }
            return totalPrice;
    
        }
    
  • + 0 comments

    Java, O(log E)

    public static int prims(int n, List<List<Integer>> edges, int start) {
                Map<Integer, List<int[]>> graph = new HashMap<>();
                for (List<Integer> edge : edges) {
                    graph.computeIfAbsent(edge.get(0), k -> new ArrayList<>()).add(new int[]{edge.get(1), edge.get(2)});
                    graph.computeIfAbsent(edge.get(1), k -> new ArrayList<>()).add(new int[]{edge.get(0), edge.get(2)});
                }
    
                PriorityQueue<int[]> pq = new PriorityQueue<>(Comparator.comparingInt(a -> a[1]));
                pq.add(new int[]{start, 0}); 
    
                boolean[] visited = new boolean[n + 1];
                int totalWeight = 0;
    
                while (!pq.isEmpty()) {
                    int[] current = pq.poll();
                    int currentNode = current[0];
                    int edgeWeight = current[1];
    
                    if (visited[currentNode]) {
                        continue;
                    }
    
                    visited[currentNode] = true;
                    totalWeight += edgeWeight;
    
                    if (graph.containsKey(currentNode)) {
                        for (int[] neighbor : graph.get(currentNode)) {
                            if (!visited[neighbor[0]]) {
                                pq.add(new int[]{neighbor[0], neighbor[1]});
                            }
                        }
                    }
                }
    
                return totalWeight;
            }
    
  • + 1 comment

    I do not get the second example. You start on A, with two options, of weight 3 (B) and 4 (C) After picking B, one have the following options: A-C (4), B-C (5), B-D (6) and B-E (2). So one pick B-E. Until then, okay.

    But now we have A-C (4) B-C (5), B-D (6) and E-C (1), so we should pick E-C. Why did the example pick A-C ?

  • + 0 comments

    Python

    def prims(n, edges, start):  
        connected = set([start])
        totalprice = 0
        while len(connected) < n:
            minprice = 10**6
            for e in edges:
                if (e[0] in connected and e[1] not in connected) or \
                   (e[1] in connected and e[0] not in connected):
                   if e[2] < minprice:
                       minprice = e[2]
                       edgeconnect = e
            connected.add(edgeconnect[0])
            connected.add(edgeconnect[1])
            totalprice += minprice            
        return totalprice
    
  • + 0 comments

    Java8

    public static int prims(int n, List<List<Integer>> edges, int start) {
        //USING PROVIDED DATA APPROACH
        
        Comparator<List<Integer>> comp = (l1, l2) -> {
            return l1.get(2) - l2.get(2);
        };
        
        Collections.sort(edges, comp);
        
        HashSet<Integer> set = new HashSet<>();
        set.add(start);
        
        int sumMin = 0;
        
        while (set.size() < n) {
            Iterator<List<Integer>> iter = edges.iterator();
                
            while (iter.hasNext()) {
                List<Integer> list = iter.next();
                
                int left = list.get(0);
                int right = list.get(1);
                int distance = list.get(2);
                
    						//Using LinkedList might speed this up
    						//Actual no need to remove already parsed list
    						// to fit set limit
                if (set.contains(left) && set.contains(right)) {
                    iter.remove();
                    continue;
                }
                                
                if ((set.contains(left) && !set.contains(right)) 
                        || (!set.contains(left) && set.contains(right))) {
                    sumMin += distance;
                    set.add(left);
                    set.add(right);
                    break;
                }
            }   
        }
        
        return sumMin;
        
        /* CREATING SUMMARY ARRAY APPROACH
        int res = 0;
        
        int[][] grid = new int[n + 1][n + 1];
        
        for (List<Integer> list : edges) {
            int i = list.get(0);
            int j = list.get(1);
            int dis = list.get(2);
            
            grid[i][j] = dis;
            grid[j][i] = dis;
        }
        
        HashSet<Integer> set = new HashSet<>();
    
        set.add(start);
        
        while (set.size() < n) {
            TreeMap<Integer, Integer> map = new TreeMap<>();
            
            for (Integer i : set) {
                for (int j = 1; j < n + 1; j ++) {
                    int curDis = grid[i][j];
                    if (!set.contains(j) && curDis != 0) {
                        map.put(curDis, j);        
                    }
                }
            }
            
            res += map.firstKey();
            set.add(map.firstEntry().getValue());
        }
        
        return res;
        */
    }