arrow-left

All pages
gitbookPowered by GitBook
1 of 7

Loading...

Loading...

Loading...

Loading...

Loading...

Loading...

Loading...

8.2. Prim's Algorithm

This section discusses Prim's Algorithm that finds a minimum spanning tree in an undirected graph.

Prim's algorithm finds a minimum spanning tree by finding the minimum edge among all incoming edges of visited vertices.

Let us define the MSTPrimarrow-up-right class inheriting the MST interface:

  • L9: adds the vertex 0 to the visited set and its incoming edges to the queue.

  • L11: iterates through all incoming edges:

    • L14: if the visited set contains the source vertex, adding the edge would create a cycle.

    • L16: if the tree contains v-1 number of edges, a spanning tree is found.

The add() method can be defined as follows:

  • L4-7: adds all incoming edges that have not been visited to the queue.

What is the worst-case complexity of Prim's Algorithm?

public class MSTPrim implements MST {
    @Override
    public SpanningTree getMinimumSpanningTree(Graph graph) {
        PriorityQueue<Edge> queue = new PriorityQueue<>();
        SpanningTree tree = new SpanningTree();
        Set<Integer> visited = new HashSet<>();
        Edge edge;

        add(queue, visited, graph, 0);

        while (!queue.isEmpty()) {
            edge = queue.poll();

            if (!visited.contains(edge.getSource())) {
                tree.addEdge(edge);
                if (tree.size() + 1 == graph.size()) break;
                add(queue, visited, graph, edge.getSource());
            }
        }

        return tree;
    }
}
  • L17: repeats the process by adding the source of the edge.

  • 8.4. Edmonds' Algorithm

    This section discusses Chu-Liu-Edmonds' Algorithm that finds a MST in a directed graph.

    Chu-Liu-Edmonds' Algorithm takes the following steps to find a MST in a directed graph:

    1. Initially, every vertex is considered a subtree.

    2. For each subtree, keep 1 incoming edge with the minimum weight.

    3. If there is no cycle, go to #5.

    4. If there is a cycle,

      1. Merge subtrees with the cycle into one and update scores for all incoming edges to this merged subtree, and goto #2.

      2. For each vertex in the subtree, add the weight of its outgoing edge chain to its incoming edges not in the subtree.

    5. Break all cycles by removing edges that cause multiple parents.

    The following demonstrates how Chu-Liu-Edmonds' Algorithm find a minimum spanning tree:

    What is the logic behind updating the edge weights related to the cycles?

    The following explains the weight updates in details:

    8.5. Quiz

    This section provides exercises for better understanding of minimum spanning trees.

    hashtag
    Complexity

    Explain the worst-case complexities of the following algorithms in terms of V and E according to our implementations:

    private void add(PriorityQueue<Edge> queue, Set<Integer> visited, Graph graph, int target) {
        visited.add(target);
    
        for (Edge edge : graph.getIncomingEdges(target)) {
            if (!visited.contains(edge.getSource()))
                queue.add(edge);
        }
    }
    private void add(PriorityQueue<Edge> queue, Set<Integer> visited, Graph graph, int target) {
        visited.add(target);
        
        graph.getIncomingEdges(target).stream().
            filter(edge -> !visited.contains(edge.getSource())).
            collect(Collectors.toCollection(() -> queue));
    }
    Prim's algorithm
  • Kruskal's algorithm

  • Chu-Liu-Edmonds' algorithm

  • hashtag
    Comparison

    Provide an example of a graph where Prim's and Kruskal's algorithms find different minimum spanning trees from the same graph and explain how these trees are found. If you cannot find an example, explain why these algorithms always find the same minimum spanning tree given the same graph.

    circle-info

    Different MSTs can be found from the same graph only if there are multiple edges with the minimum weight for any of which can be polled from the priority queue. Consider cases where the compareTo() method is overridden differently from the original implementation.

    hashtag
    Report

    Write a report quiz7.pdf that includes the complexity and comparison analyses.

    8.1. Abstraction

    This section discusses spanning trees in a graph.

    hashtag
    Overview

    A spanning tree in a graph is a tree that contains all vertices in the graphs as its nodes. A minimum spanning tree is a spanning tree whose sum of all edge weights is the minimum among all the other spanning trees in the graph.

    Can a graph have more than one minimum spanning tree?

    hashtag
    Spanning Tree

    Let us define the class under the package:

    • L1: inherits the interface.

    • L2: contains all edges in this spanning tree.

    • L3

    We then define getters and setters:

    • L3: the size of the spanning tree is determined by the number of edges.

    Finally, we override the compareTo() method that makes the comparison to another spanning tree by the total weight:

    hashtag
    MST

    Let us create the interface that is inherited by all minimum spanning tree algorithms:

    • L2: an abstract method that takes a graph and returns a minimum spanning tree.

    8.3. Kruskal’s Algorithm

    This section discusses Kruskal's Algorithm that finds a minimum spanning tree in an undirected graph.

    Kruskal's algorithm finds a minimum spanning tree by finding the minimum edge among subtrees.

    Let us create the class inheriting the MST interface:

    • L4: adds all edges to the priority queue.

    : contains the total weight of this spanning tree.
    SpanningTreearrow-up-right
    graph.spanarrow-up-right
    Comparablearrow-up-right
    MSTarrow-up-right

    L5: creates a forest where each vertex is considered a separate tree.

  • L8: iterates through all edges:

    • L11: if the target and source vertices in the edge are not in the same tree.

    • L13: if the tree contains v-1 number of edges, a spanning tree is found.

    • L14: merges the target and source vertices into the same tree.

  • MSTKruskalarrow-up-right
    public class SpanningTree implements Comparable<SpanningTree> {
        private final List<Edge> edges;
        private double total_weight;
    
        public SpanningTree() {
            edges = new ArrayList<>();
        }
    
        public SpanningTree(SpanningTree tree) {
            edges = new ArrayList<>(tree.getEdges());
            total_weight = tree.getTotalWeight();
        }
    }
    public List<Edge> getEdges() { return edges; }
    public double getTotalWeight() { return total_weight; }
    public int size() { return edges.size(); }
    
    public void addEdge(Edge edge) {
        edges.add(edge);
        total_weight += edge.getWeight();
    }
    @Override
    public int compareTo(SpanningTree tree) {
        double diff = total_weight - tree.total_weight;
        if (diff > 0) return 1;
        else if (diff < 0) return -1;
        else return 0;
    }
    public interface MST {
        public SpanningTree getMinimumSpanningTree(Graph graph);
    }
    public class MSTKruskal implements MST {
        @Override
        public SpanningTree getMinimumSpanningTree(Graph graph) {
            PriorityQueue<Edge> queue = new PriorityQueue<>(graph.getAllEdges());
            DisjointSet forest = new DisjointSet(graph.size());
            SpanningTree tree = new SpanningTree();
    
            while (!queue.isEmpty()) {
                Edge edge = queue.poll();
    
                if (!forest.inSameSet(edge.getTarget(), edge.getSource())) {
                    tree.addEdge(edge);
                    if (tree.size() + 1 == graph.size()) break;
                    forest.union(edge.getTarget(), edge.getSource());
                }
            }
    
            return tree;
        }
    }

    8. Minimum Spanning Trees

    This chapter discusses algorithms to find minimum spanning trees in undirected and directed graphs.

    hashtag
    Contents

    1. Abstraction

    hashtag
    References

    Prim's Algorithm
    Kruskal's Algorithm
    Chu-Liu-Edmonds' Algorithm
    Quiz
    Homework
    Prim's Algorithmarrow-up-right
    Kruskal's Algorithmarrow-up-right
    Chu-Liu-Edmonds' Algorithmarrow-up-right

    8.6. Homework

    This section describes the homework assignment to develop an algorithm to find all minimum spanning tress given an undirected graph.

    hashtag
    Finding All Minimum Spanning Trees

    Your task is to write a program that finds all minimum spanning trees given an undirected graph.

    hashtag
    Tasks

    • Create a class called that inherits the interface.

    • Override the getMinimumSpanningTrees() method.

    • Feel free to use any classes in the package without modifying.

    circle-info

    You may want to start with the implementation of either or algorithm and update the code to find all minimum spanning trees.

    hashtag
    Extra Credit

    • Create an interesting graph and submit both the source code (as in ) and the diagram representing your graph (up to 1 point).

    hashtag
    Notes

    • Test your code with graphs consisting of zero to many spanning trees.

    • Your output must include only minimum spanning trees.

    • Your output should not include redundant trees. For example, if there are three vertices, 0, 1, and 2, {0 -> 1, 0 -> 2

    Write a report that explains the logic and worst-case complexity of your program and save it as hw3.pdf.

    } is considered the same as {
    0 -> 1
    ,
    0 <- 2
    } or {
    0 <- 1
    ,
    0 -> 2
    } or {
    0 <-1
    ,
    0 <- 2
    }.
    MSTAllHWarrow-up-right
    MSTAllarrow-up-right
    grapharrow-up-right
    Prim's
    Kruskal's
    MSTAllHWTestarrow-up-right