search
HomeJavajavaTutorialMinimum Spanning Trees

A minimum spanning tree of a graph is a spanning tree with the minimum total weights.

A graph may have many spanning trees. Suppose that the edges are weighted. A minimum spanning tree has the minimum total weights. For example, the trees in Figures below b, c, d are spanning trees for the graph in Figure a. The trees in Figures c and d are minimum spanning trees.

Minimum Spanning Trees

The problem of finding a minimum spanning tree has many applications. Consider a company with branches in many cities. The company wants to lease telephone lines to connect all the branches together. The phone company charges different amounts of money to connect different pairs of cities. There are many ways to connect all branches together. The cheapest way is to find a spanning tree with the minimum total rates.

Minimum Spanning Tree Algorithms

How do you find a minimum spanning tree? There are several well-known algorithms for doing so. This section introduces Prim’s algorithm. Prim’s algorithm starts with a spanning tree T that contains an arbitrary vertex. The algorithm expands the tree by repeatedly adding a vertex with the lowest-cost edge incident to a vertex already in the tree. Prim’s algorithm is a greedy algorithm, and it is described in code below.

Input: A connected undirected weighted G = (V, E) with non-negative weights
 Output: MST (a minimum spanning tree)
 1 MST minimumSpanningTree() {
 2 Let T be a set for the vertices in the spanning tree;
 3 Initially, add the starting vertex to T;
 4
 5 while (size of T 



<p>The algorithm starts by adding the starting vertex into <strong>T</strong>. It then continuously adds a vertex (say <strong>v</strong>) from <strong>V – T</strong> into <strong>T</strong>. <strong>v</strong> is the vertex that is adjacent to the vertex in <strong>T</strong> with the smallest weight on the edge. For example, there are five edges connecting vertices in <strong>T</strong> and <strong>V – T</strong> as shown in Figure below, and (<strong>u</strong>, <strong>v</strong>) is the one with the smallest weight.</p>

<p><img src="/static/imghwm/default1.png" data-src="https://img.php.cn/upload/article/000/000/000/172557408574612.jpg?x-oss-process=image/resize,p_40" class="lazy" alt="Minimum Spanning Trees"></p>

<p>Consider the graph in Figure below. The algorithm adds the vertices to <strong>T</strong> in this order:</p>

<p><img src="/static/imghwm/default1.png" data-src="https://img.php.cn/upload/article/000/000/000/172557408660759.jpg?x-oss-process=image/resize,p_40" class="lazy" alt="Minimum Spanning Trees"></p>

<ol>
<li>Add vertex <strong>0</strong> to <strong>T</strong>.</li>
<li>Add vertex <strong>5</strong> to <strong>T</strong>, since <strong>Edge(5, 0, 5)</strong> has the smallest weight among all edges incident to a vertex in <strong>T</strong>, as shown in Figure a. The arrow line from <strong>0</strong> to <strong>5</strong> indicates that <strong>0</strong> is the parent of <strong>5</strong>.</li>
<li>Add vertex <strong>1</strong> to <strong>T</strong>, since <strong>Edge(1, 0, 6)</strong> has the smallest weight among all edges incident to a vertex in <strong>T</strong>, as shown in Figure b.</li>
<li>Add vertex <strong>6</strong> to <strong>T</strong>, since <strong>Edge(6, 1, 7)</strong> has the smallest weight among all edges incident to a vertex in <strong>T</strong>, as shown in Figure c.</li>
<li>Add vertex <strong>2</strong> to <strong>T</strong>, since <strong>Edge(2, 6, 5)</strong> has the smallest weight among all edges incident to a vertex in <strong>T</strong>, as shown in Figure d.</li>
<li>Add vertex <strong>4</strong> to <strong>T</strong>, since <strong>Edge(4, 6, 7)</strong> has the smallest weight among all edges incident to a vertex in <strong>T</strong>, as shown in Figure e.</li>
<li>Add vertex <strong>3</strong> to <strong>T</strong>, since <strong>Edge(3, 2, 8)</strong> has the smallest weight among all edges incident to a vertex in <strong>T</strong>, as shown in Figure f.</li>
</ol>

<p>A minimum spanning tree is not unique. For example, both (c) and (d) in Figure below are minimum spanning trees for the graph in Figure a. However, if the weights are distinct, the graph has a unique minimum spanning tree.</p>

<p><img src="/static/imghwm/default1.png" data-src="https://img.php.cn/upload/article/000/000/000/172557408958347.jpg?x-oss-process=image/resize,p_40" class="lazy" alt="Minimum Spanning Trees"></p>

<p>Assume that the graph is connected and undirected. If a graph is not connected or directed, the algorithm will not work. You can modify the algorithm to find a spanning forest for any undirected graph. A spanning forest is a graph in which each connected component is a tree.</p>

<h2>
  
  
  Refining Prim’s MST Algorithm
</h2>

<p>To make it easy to identify the next vertex to add into the tree, we use <strong>cost[v]</strong> to store the cost of adding a vertex <strong>v</strong> to the spanning tree <strong>T</strong>. Initially <strong>cost[s]</strong> is <strong>0</strong> for a starting vertex and assign infinity to <strong>cost[v]</strong> for all other vertices. The algorithm repeatedly finds a vertex <strong>u</strong> in <strong>V – T</strong> with the smallest <strong>cost[u]</strong> and moves <strong>u</strong> to <strong>T</strong>. The refined version of the alogrithm is given in code below.<br>
</p>

<pre class="brush:php;toolbar:false">Input: A connected undirected weighted G = (V, E) with non-negative weights
Output: a minimum spanning tree with the starting vertex s as the root
 1 MST getMinimumSpanngingTree(s) {
 2 Let T be a set that contains the vertices in the spanning tree;
 3 Initially T is empty;
 4 Set cost[s] = 0; and cost[v] = infinity for all other vertices in V;
 5
 6 while (size of T  w(u, v)) { // Adjust cost[v]
11 cost[v] = w(u, v); parent[v] = u;
12 }
13 }
14 }

Implementation of the MST Algorithm

The getMinimumSpanningTree(int v) method is defined in the WeightedGraph class. It returns an instance of the MST class, as shown in Figure below.

Minimum Spanning Trees

The MST class is defined as an inner class in the WeightedGraph class, which extends the Tree class, as shown in Figure below.

Minimum Spanning Trees

The Tree class was shown in Figure below. The MST class was implemented in lines 141–153 in WeightedGraph.java.

Minimum Spanning Trees

The refined version of the Prim’s algoruthm greatly simplifies the implementation. The getMinimumSpanningTree method was implemented using the refined version of the Prim’s algorithm in lines 99–138 in Listing 29.2. The getMinimumSpanningTree(int startingVertex) method sets cost[startingVertex] to 0 (line 105) and cost[v] to infinity for all other vertices (lines 102–104). The parent of startingVertex is set to -1 (line 108). T is a list that stores the vertices added into the spanning tree (line 111). We use a list for T rather than a set in order to record the order of the vertices added to T.

Initially, T is empty. To expand T, the method performs the following operations:

  1. Find the vertex u with the smallest cost[u] (lines 118–123 and add it into T (line 125).
  2. After adding u in T, update cost[v] and parent[v] for each v adjacent to u in V-T if cost[v] > w(u, v) (lines 129–134).

After a new vertex is added to T, totalWeight is updated (line 126). Once all vertices are added to T, an instance of MST is created (line 137). Note that the method will not work if the graph is not connected. However, you can modify it to obtain a partial MST.

The MST class extends the Tree class (line 141). To create an instance of MST, pass root, parent, T, and totalWeight (lines 144-145). The data fields root, parent, and searchOrder are defined in the Tree class, which is an inner class defined in AbstractGraph.

Note that testing whether a vertex i is in T by invoking T.contains(i) takes O(n) time, since T is a list. Therefore, the overall time complexity for this implemention is O(n3).

The code below gives a test program that displays minimum spanning trees for the graph in Figure below and the graph in Figure below a, respectively.

Minimum Spanning Trees

Minimum Spanning Trees

package demo;

public class TestMinimumSpanningTree {

    public static void main(String[] args) {
        String[] vertices = {"Seattle", "San Francisco", "Los Angeles", "Denver", "Kansas City", "Chicago", "Boston", "New York", "Atlanta", "Miami", "Dallas", "Houston"};

        int[][] edges = {
                {0, 1, 807}, {0, 3, 1331}, {0, 5, 2097},
                {1, 0, 807}, {1, 2, 381}, {1, 3, 1267},
                {2, 1, 381}, {2, 3, 1015}, {2, 4, 1663}, {2, 10, 1435},
                {3, 0, 1331}, {3, 1, 1267}, {3, 2, 1015}, {3, 4, 599}, {3, 5, 1003},
                {4, 2, 1663}, {4, 3, 599}, {4, 5, 533}, {4, 7, 1260}, {4, 8, 864}, {4, 10, 496},
                {5, 0, 2097}, {5, 3, 1003}, {5, 4, 533}, {5, 6, 983}, {5, 7, 787},
                {6, 5, 983}, {6, 7, 214},
                {7, 4, 1260}, {7, 5, 787}, {7, 6, 214}, {7, 8, 888},
                {8, 4, 864}, {8, 7, 888}, {8, 9, 661}, {8, 10, 781}, {8, 11, 810},
                {9, 8, 661}, {9, 11, 1187},
                {10, 2, 1435}, {10, 4, 496}, {10, 8, 781}, {10, 11, 239},
                {11, 8, 810}, {11, 9, 1187}, {11, 10, 239}
        };

        WeightedGraph<string> graph1 = new WeightedGraph(vertices, edges);
        WeightedGraph<string>.MST tree1 = graph1.getMinimumSpanningTree();
        System.out.println("Total weight is " + tree1.getTotalWeight());
        tree1.printTree();

        edges = new int[][]{
            {0, 1, 2}, {0, 3, 8},
            {1, 0, 2}, {1, 2, 7}, {1, 3, 3},
            {2, 1, 7}, {2, 3, 4}, {2, 4, 5},
            {3, 0, 8}, {3, 1, 3}, {3, 2, 4}, {3, 4, 6},
            {4, 2, 5}, {4, 3, 6}
        };

        WeightedGraph<integer> graph2 = new WeightedGraph(edges, 5);
        WeightedGraph<integer>.MST tree2 = graph2.getMinimumSpanningTree(1);
        System.out.println("\nTotal weight is " + tree2.getTotalWeight());
        tree2.printTree();
    }

}

</integer></integer></string></string>

Total weight is 6513.0
Root is: Seattle
Edges: (Seattle, San Francisco) (San Francisco, Los Angeles)
(Los Angeles, Denver) (Denver, Kansas City) (Kansas City, Chicago)
(New York, Boston) (Chicago, New York) (Dallas, Atlanta)
(Atlanta, Miami) (Kansas City, Dallas) (Dallas, Houston)

Total weight is 14.0
Root is: 1
Edges: (1, 0) (3, 2) (1, 3) (2, 4)

プログラムは、27 行目で上の図の重み付きグラフを作成します。次に、getMinimumSpanningTree() (28 行目) を呼び出して、その最小スパニング ツリーを表す MST を返します。グラフ。 MST オブジェクトで printTree() (行 30) を呼び出すと、ツリーのエッジが表示されます。 MSTTree のサブクラスであることに注意してください。 printTree() メソッドは、Tree クラスで定義されています。

最小スパニングツリーの図を下の図に示します。頂点は、シアトル、サンフランシスコ、ロサンゼルス、デンバー、カンザスシティ、ダラス、ヒューストン、シカゴ、ニューヨーク、ボストン、アトランタ、マイアミの順序でツリーに追加されます。

Minimum Spanning Trees

The above is the detailed content of Minimum Spanning Trees. For more information, please follow other related articles on the PHP Chinese website!

Statement
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
How do I use Maven or Gradle for advanced Java project management, build automation, and dependency resolution?How do I use Maven or Gradle for advanced Java project management, build automation, and dependency resolution?Mar 17, 2025 pm 05:46 PM

The article discusses using Maven and Gradle for Java project management, build automation, and dependency resolution, comparing their approaches and optimization strategies.

How do I create and use custom Java libraries (JAR files) with proper versioning and dependency management?How do I create and use custom Java libraries (JAR files) with proper versioning and dependency management?Mar 17, 2025 pm 05:45 PM

The article discusses creating and using custom Java libraries (JAR files) with proper versioning and dependency management, using tools like Maven and Gradle.

How do I implement multi-level caching in Java applications using libraries like Caffeine or Guava Cache?How do I implement multi-level caching in Java applications using libraries like Caffeine or Guava Cache?Mar 17, 2025 pm 05:44 PM

The article discusses implementing multi-level caching in Java using Caffeine and Guava Cache to enhance application performance. It covers setup, integration, and performance benefits, along with configuration and eviction policy management best pra

How can I use JPA (Java Persistence API) for object-relational mapping with advanced features like caching and lazy loading?How can I use JPA (Java Persistence API) for object-relational mapping with advanced features like caching and lazy loading?Mar 17, 2025 pm 05:43 PM

The article discusses using JPA for object-relational mapping with advanced features like caching and lazy loading. It covers setup, entity mapping, and best practices for optimizing performance while highlighting potential pitfalls.[159 characters]

How does Java's classloading mechanism work, including different classloaders and their delegation models?How does Java's classloading mechanism work, including different classloaders and their delegation models?Mar 17, 2025 pm 05:35 PM

Java's classloading involves loading, linking, and initializing classes using a hierarchical system with Bootstrap, Extension, and Application classloaders. The parent delegation model ensures core classes are loaded first, affecting custom class loa

See all articles

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

AI Hentai Generator

AI Hentai Generator

Generate AI Hentai for free.

Hot Article

R.E.P.O. Energy Crystals Explained and What They Do (Yellow Crystal)
4 weeks agoBy尊渡假赌尊渡假赌尊渡假赌
R.E.P.O. Best Graphic Settings
4 weeks agoBy尊渡假赌尊渡假赌尊渡假赌
R.E.P.O. How to Fix Audio if You Can't Hear Anyone
4 weeks agoBy尊渡假赌尊渡假赌尊渡假赌
R.E.P.O. Chat Commands and How to Use Them
4 weeks agoBy尊渡假赌尊渡假赌尊渡假赌

Hot Tools

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

ZendStudio 13.5.1 Mac

ZendStudio 13.5.1 Mac

Powerful PHP integrated development environment

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment

MinGW - Minimalist GNU for Windows

MinGW - Minimalist GNU for Windows

This project is in the process of being migrated to osdn.net/projects/mingw, you can continue to follow us there. MinGW: A native Windows port of the GNU Compiler Collection (GCC), freely distributable import libraries and header files for building native Windows applications; includes extensions to the MSVC runtime to support C99 functionality. All MinGW software can run on 64-bit Windows platforms.

Atom editor mac version download

Atom editor mac version download

The most popular open source editor