Prim algorithm (minimum spanning tree) is one of the ten common algorithms I know

Time:2021-12-2

Preface requirements


Today we are learning the prim algorithm. Let’s introduce it from a scene

Prim algorithm (minimum spanning tree) is one of the ten common algorithms I know

There are 7 villages (a, B, C, D, e, F, g). Now roads need to be built to connect the 7 villages

1. Distance between villagesExpress (weight) with a sidelineFor example, a – B is 5km away

2. AskHow to build roads to ensure that all villages can be connected and the total mileage of roads built is the shortest?

Our idea is to choose as few routes as possible, and each route is the smallest to ensure the minimum total mileage

1、 What is prim algorithm

Prim algorithm: the minimum spanning tree is inConnected graph with n verticesFind outConnected subgraphs with only (n-1) edges containing all n vertices, that is, the so-called minimal connected subgraph

Prim algorithm (minimum spanning tree) is one of the ten common algorithms I know

2、 Understand prim algorithm through examples

In fact, the essence of road construction is the problem of minimum spanning tree

First, let’s introduce the minimum cost spanning tree (MST)

So what is the minimum spanning tree? In fact, given aWeighted undirected connected graph, howSelect a spanning tree to minimize the sum of weights on all edges of the tree。 This is called minimum spanning tree

So what are the characteristics of minimum spanning tree?

1. If there are n vertices, there must be at least n-1 edges
2. The graph should contain all vertices
3. All edges of n-1 shall be in the figure

Prim algorithm (minimum spanning tree) is one of the ten common algorithms I know

Then the algorithms for finding the minimum spanning tree mainly include prim algorithm and Kruskal algorithm

Analysis of prim algorithm

1. Let g = (V, e) be a connected network, t = (U, d) be a minimum spanning tree, V, u be a vertex set, and E, d be a set of edges

2. If the minimum spanning tree is constructed from vertex u, take the vertex u from set V and put it into set u, and mark the visited [u] = 1 of vertex v

3. If there are edges between vertex UI in set u and vertex VJ in set V-U, find the edge with the smallest weight among these edges, but it cannot form a loop.

Add vertex VJ to set u, add edge (UI, VJ) to set D, and mark visited [VJ] = 1

4. Repeat step ② until u and V are equal, that is, all vertices are marked as visited, and there are n-1 edges in D

Graphical analysis of prim algorithm

1. If you start processing from vertex a, put a into the set and connect to other vertices, including C, G and B

Prim algorithm (minimum spanning tree) is one of the ten common algorithms I know

2. At this time, the minimum weight value of these three edges is A-G, which is 2, so we put g into the set, a, G

Prim algorithm (minimum spanning tree) is one of the ten common algorithms I know

3. At this time, the minimum weight value of these five edges is B-B is 3, so we put B into the set, a, G, B

Prim algorithm (minimum spanning tree) is one of the ten common algorithms I know

4. At this time, the minimum weight value of these four edges is G-E is 4, so we put e into the set, a, G, B, e

Prim algorithm (minimum spanning tree) is one of the ten common algorithms I know

At this time, the minimum weight value of these five edges is E-F is 5, and so on

The final set result should be < A, G, B, e, F, D, C >

Prim algorithm (minimum spanning tree) is one of the ten common algorithms I know

Analysis of prim code ideas

1. We need a char array to store vertices and the number of edges of vertices
2. We need to use adjacency matrix to represent the connection and weight value between vertices
3. We need to generate mintree tree
4. We need to create a map

Prim algorithm code practice

1. The adjacency matrix is used to represent the connection relationship and weight value between graphs

Prim algorithm (minimum spanning tree) is one of the ten common algorithms I know

//Use the adjacency matrix to describe the weight value, indicating that 0 represents none
int[][] weight = new int[][]{
        {0,5,7,0,0,0,2},
        {5,0,0,9,0,0,3},
        {7,0,0,0,8,0,0},
        {0,9,0,0,0,4,0},
        {0,0,8,0,0,5,4},
        {0,0,0,4,5,0,6},
        {2,3,0,0,4,6,0}
};

2. You need a char array to store vertices and the number of edges of vertices

//Char [] number of vertices stored in array
char[] data = new char[]{'A','B','C','D','E','F','G'};

int verxs = data.length;

3. Create drawing objects

class MGraph{

    int verxs;// Represents the number of nodes in the graph
    char[] data;// Store node data
    int[][] weight;// Storage edge

    public MGraph(int verxs) {
        this.verxs = verxs;
        data = new char[verxs];
        weight = new int[verxs][verxs];
    }
}

4. We need to create these values and arrays, assign them to graph objects, and create methods to output graphs

class MinTree{

    //Create adjacency matrix of graph
    public void createGraph(MGraph graph,int verxs,char[] data,int[][] weight){

        for ( int i = 0 ; i<verxs;i++){
            //Assign the value in the char array to the graph
            graph.data[i] = data[i];
            for (int j = 0; j<verxs;j++ ){
                //Assign the value in weight to the graph
                graph.weight[i][j] = weight[i][j];
            }
        }
    }

    //Print the information of the diagram
    public void showGraph(MGraph graph){
        for ( int[] link : graph.weight){
            System.out.println(Arrays.toString(link));
        }
    }
}

Next, we use the demo to complete the creation and output of the diagram

public static void main(String[] args) {

        //Char [] number of vertices stored in array
        char[] data = new char[]{'A','B','C','D','E','F','G'};

        //Edges between vertices
        int verxs = data.length;

        //Use the adjacency matrix to describe the weight value, indicating that 0 represents none
        int[][] weight = new int[][]{
                {0,5,7,0,0,0,2},
                {5,0,0,9,0,0,3},
                {7,0,0,0,8,0,0},
                {0,9,0,0,0,4,0},
                {0,0,8,0,0,5,4},
                {0,0,0,4,5,0,6},
                {2,3,0,0,4,6,0}
        };

        MGraph graph = new MGraph(verxs);
        MinTree minTree = new MinTree();
        minTree.createGraph(graph,verxs,data,weight);
        minTree.showGraph(graph);
}

Prim algorithm (minimum spanning tree) is one of the ten common algorithms I know

Write algorithm code according to prim algorithm

1. Our idea is to start by finding a vertex and constantly find adjacent vertices, such as a

The conditions for finding adjacent vertices are:A is accessed, other vertices are not accessed

2.Judge whether the weight of a-other vertices is the smallest

In order to find the smallest, we use a large number instead of the one just mentioned:0

public void prim(MGraph graph,int v){
        //Use an array to mark whether a node has been accessed
        int[] visited = new int[graph.verxs];

        for ( int i=0; i<visited.length; i++){
            visited[i] = 0;
        }

        //Label the current node as accessed
        visited[v] = 1;

        int h1 = -1;
        int h2 = -1;
        int minWeight = 10000;
        for(int k = 1; k < graph.verxs; k++) {
            for(int i = 0; i < graph.verxs; i++) {
                for(int j = 0; j< graph.verxs;j++) {
                    if(visited[i] == 1 && visited[j] == 0 && graph.weight[i][j] < minWeight) {
                        minWeight = graph.weight[i][j];
                        h1 = i;
                        h2 = j;
                    }
                }
            }
            System. Out. Println ("edge <" + graph. Data [H1] + "," + graph. Data [H2] + "> weight:" + minweight ");
            visited[h2] = 1;
            minWeight = 10000;
        }
    }

About to the above figure0 --> 10000

public static void main(String[] args) {

    //Char [] number of vertices stored in array
    char[] data = new char[]{'A','B','C','D','E','F','G'};

    //Edges between vertices
    int verxs = data.length;

    //Use the adjacency matrix to describe the weight value, indicating that 0 represents none
    int[][] weight = new int[][]{
            {10000,5,7,10000,10000,10000,2},
            {5,10000,10000,9,10000,10000,3},
            {7,10000,10000,10000,8,10000,10000},
            {10000,9,10000,10000,10000,4,10000},
            {10000,10000,8,10000,10000,5,4},
            {10000,10000,10000,4,5,10000,6},
            {2,3,10000,10000,4,6,10000}
    };

    MGraph graph = new MGraph(verxs);
    MinTree minTree = new MinTree();
    minTree.createGraph(graph,verxs,data,weight);
    minTree.showGraph(graph);
    minTree.prim(graph,0);
}

The operation results are as follows:
Edge < A, G > weight: 2
Edge < g, b > weight: 3
Edge < g, E > weight: 4
Edge < e, f > weight: 5
Edge < F, d > weight: 4
Edge < A, C > weight: 7

Algorithms for finding the minimum spanning tree

reference material


  • Shang Silicon Valley: data structure and algorithm (Mr. Han Shunping):Prim algorithm