Data structure (v) premium Manaus and Kruskal minimum spanning tree (Swift Object-oriented version)

Source: Internet
Author: User

Last blog we talked about the physical storage structure adjacency matrix and adjacency linked list, and then gives the depth-first search and breadth-first search of graph. This blog post on the basis of the previous blog to extend, but also about the map. Today's blog mainly introduces two algorithms, are about the minimum spanning tree, one is the prim algorithm, the other is the Kruskal algorithm. These two algorithms are very classical, but also the more important algorithm in the graph.

Today's blog will first talk about how the prim algorithm generates the minimum spanning tree, and then gives a sample diagram of the concrete steps, and finally gives the specific code implementation and tests. Of course the Kruskal algorithm will also give a concrete example diagram, and then give the specific code and test cases. Of course, the demo in this blog is implemented on the basis of the previous blog post. Because in the previous blog we have created a ready-made map, this blog will be brought directly to use.

At the beginning of this blog, let's briefly talk about what is the minimum spanning tree. The minimum spanning tree is the smallest connected sub-graph of the original image, meaning that the sub-graph is connected and has no redundant edges, and does not form a loop. Most importantly, the weights of all edges of the minimum spanning tree are added to the minimum, which is also the source of the smallest spanning tree . In connection with real life, that is, some villages need to access the telephone line, how to make each village can phone line and the most provincial materials. In other words, each village is connected, and the total line is the shortest, if the line is connected, is actually our blog to talk about the smallest spanning tree.

First, premium Manaus algorithm

Next we'll talk about the Prim algorithm. In fact, the main idea of the prim algorithm to create a minimum spanning tree is to select the smallest weights from the candidate nodes to be added to the minimum spanning tree. The diagram we created earlier uses the prim algorithm to create the complete process of a minimal spanning tree. The red Edge is the candidate node for each step to make a connected arc, from the candidate edges to select the least weight of the edge added to the minimum spanning tree, we can consider it as a positive process.

Once a node is regularized, the radian connected to its positive node is considered a candidate radian, of course the nodes to which the candidate radians are connected must be a point other than the smallest spanning tree. If the point that the candidate Radian is connected to is on the smallest spanning tree, discard the candidate node. Until there is no candidate radian, the creation of the minimum spanning tree is complete.

This is a good representation of the process, where the connection between the candidate nodes is marked with red, and the radian between the positive nodes is expressed in black. By following this idea, we will eventually generate the minimum spanning tree we need.

1.Prim algorithm parsing

    • (0): This is the structure of the graph created by our previous blog, and each arc has the right value.
  • (1): We create a minimum spanning tree with a node as the root of the minimal spanning tree, and the A node is the B and F nodes, so these two nodes are the candidate nodes for this step. Because (a--10--b) < (a--11--f), so we will be the candidate node in the minimum value of the B node regularization.
  • (2): positive b , and use the black line for labeling, now A, B nodes are in the smallest spanning tree. After the b node is regularized, we add those nodes that are connected to the B node but not in the minimal spanning tree to the set of candidate nodes, at which point the candidate nodes for the minimum spanning tree are: (b--18--c), (B--12--i), (B--16--g), (a--11--f).
  • (3): From the candidate node left in the previous step, we can see that the a--11--f this edge of the minimum weight , so the F-node regularization into the minimum spanning tree. Because the e-node is connected to the newly-regularized F-junction, the E-nodes are added to the candidate node set. The candidate nodes for the minimum spanning tree at this time are: (b--18--c), (B--12--i), (B--16--g), (F--17--g), (F--26--E).
  • (4): Where the b--12--i of the edge with the candidate node is the least, we will be positive, and will be in the I-connected D node added to the candidate node. The candidate nodes for the minimum spanning tree at this time are: (b--18--c), (B--16--g), (F--17--g), (F--26--E), (i--8--c), (i--21--d).
  • (5): The candidate nodes at the moment are C, G, E, D. Because I--8--C is the least radian in the candidate node, so C is regularized. Because the C node is regularized, the candidate nodes to the C node are removed. Add the points connected to the C node to the candidate node collection, where the candidate radians for the smallest spanning tree are: (b--16--g), (F--17--g), (F--26--E), (i--21--d), (c--22--d).
  • (6): From the above candidate Radian, we can easily see (b--16--g) the weight of the smallest, so the G-node to be positive. After the G node is regularized, then the set of candidate nodes is: (F--26--E), (i--21--d), (c--22--d), (g--19--h), (g--24--d).
  • (7): or choose the smallest to be positive, the minimum weight of the above candidate set is ( g--19--h), so the node H regularization. Add (H--7--E), (h--16--d) to the candidate set, at which time the candidate set is: (F--26--E), (i--21--d), (c--22--d), (g--24--d), (H--7--E), (h--16--d).
  • (8): The above candidate concentration (H--7--E) is the smallest, so the e node is regularized, the candidate node after the positive e nodes are: (i--21--d), (c--22--d), (g--24--d), (h--16--d), (e--20--d).
  • (9): In the candidate set to the D node of the minimum weight is (h--16--d), so the D node regularization, and H-node connected. Because the D node is positive, all radians that reach the D node in the candidate node are removed from the candidate node, so the candidate set is empty at the moment. When the candidate set is empty, it means that our minimum spanning tree is generated.
  • (10): The smallest spanning tree that we eventually generate.

2. Code implementation of the above process

If you understand the above process, it is not difficult to give the code the implementation. We take the adjacency list as an example, the representation of the prim algorithm of the minimum spanning tree of the adjacency matrix is not too much to repeat here, but the demo shared on Github is related to the prim algorithm of the adjacency matrix. The code below is a concrete implementation of the prim algorithm in the adjacency list.

In the method below, the first parameter, index, is the one that was last regularized added to the smallest spanning tree in an array of contiguous linked lists. The second parameter, Leafnotes, is a candidate leaf node that can be regularized. The third parameter, Adjvex , is the node that has been added to the minimum spanning tree.

The code below is mainly divided into the following steps:

    1. Find nodes that are connected to the last-positive node and are not in the Adjvex array, adding them to the candidate collection.
    2. The edge with the least weight is found from the candidate set, and the node connected to the edge is determined to be regularized.
    3. Add the node you looked for in the previous step to our new adjacency list.
    4. Remove the node that has been regularized from the candidate union.
    5. Adds the node that has been regularized to the adjves array.
    6. Recursive this just regularization node.

  

3. Test results

Below is the smallest spanning tree created by our code above, and of course we still use the adjacency list to store our minimal spanning tree , which is the storage structure of the adjacency list of our smallest spanning tree, and the result of the traversal of the smallest spanning tree.

  

The above is the smallest spanning tree generated on the adjacency list and the result of the traversal, below is the smallest spanning tree generated by the adjacency matrix and the result of the traversal.

  

Second, Kruskal algorithm

In the last part we explain the whole process of the prim algorithm in detail, then we will talk about another classical algorithm Kruskal algorithm of the minimum spanning tree. The core idea of the Kruskal algorithm is to sort each edge by its weight from small to large, then add the smallest edge from the ordered set to the smallest spanning tree, but ensure that the edges on the newly added edge and the smallest spanning tree do not form a loop. The specific algorithm steps are given below and the specific code implementation is given.

Schematic diagram of the 1.Kruskal algorithm

First we have to sort the relationship between the nodes, which is the relation array we used earlier, and sort by the size of the weights, which is the result of our sorting. The edges we need to build the "minimal spanning tree" are removed from the relationship below, and before we join the smallest spanning tree, we first determine whether the removed edges are joined to the minimum spanning tree to form a loop. If the loop is not formed, it is added into the minimum spanning tree, and if the loop is formed, then the edge is discarded. Below is the set of relationships that we arrange according to the weight values.

    

The bottom is to remove the edges from the above set, one to insert the data into the new adjacency list, insert the edge when we want to determine whether it will form a loop in the smallest spanning tree, if the loop is formed, then the edge is discarded and the next edge is obtained.

  

2. Find the tail node of the node

In the above algorithm, it is the key of the algorithm to determine whether the newly added edges form a loop in the minimum spanning tree . Below is to determine whether the two nodes to be connected to form a loop in the smallest spanning tree, when the tail nodes of the two nodes are unequal, it is stated that connecting two points does not constitute a loop in the smallest spanning tree. When two nodes have a common tail node, it is indicated that a loop is formed in the smallest spanning tree after the connection, and the schematic diagram is as follows:

  

This method is to find the tail node of a node, the parent is stored in the index corresponding to the node's Tail node index, the following code fragment is to look for the node's tail node index to return.

  

3, the Kruskal algorithm's concrete realization

The code snippet below is the implementation of the Kruskal algorithm, first of all we initialize an adjacency linked list through the Configminitree () method, which is used to store our smallest spanning tree. Then we sort the set of nodes and radians according to weights from small to large. After sorting, this ordered collection is traversed by a for loop, adding those edges that do not form the loop into our smallest spanning tree. The specific code is shown below.

1     /**2 Create minimum spanning tree: Kruskal3      */4 func Createminispantreekruskal () {5Print ("Kruskal algorithm:")6 Configminitree ()7         //sort weights from small to large8Let sortrelation = relation.sorted {(item1, item2), Boolinch9             returnInt (item1.2 as! NSNumber) < Int (item2.2 as!nsnumber)Ten         } One          A         //record the tail node of a node to avoid a closed loop -         varParent = Array.init (repeating:-1, Count:miniTree.count) -          the          forIteminchsortrelation { -Let Beginnoteindex = self.relationdic[item.0 as! string]! -Let Endnoteindex = self.relationdic[item.1 as! string]! -Let Weightnumber = item.2 as!Int +              -Let Preendindex =Findendindex (parent:parent, Index:beginnoteindex) +Let Nextendindex =Findendindex (parent:parent, Index:endnoteindex) A              atPrint ("\ (beginnoteindex)--\ (weightnumber)-->\ (Endnoteindex)") -              -             ifPreendindex! =Nextendindex { -                  -Parent[preendindex] = Nextendindex//Update Tail node - Insertnotetominitree (Preindex:beginnoteindex, in Linkindex:endnoteindex, - weightnumber:weightnumber); to             } +         } -          the displaygraph (Graph:minitree) *     } $     Panax Notoginseng     ///Insert the appropriate node into the new adjacency list - private func Insertnotetominitree (Preindex:int, the Linkindex:int, + weightnumber:int) { ALet note =Graphadjacencylistnote (Data:linkindex as Anyobject, the Weightnumber:weightnumber, + Prenoteindex:preindex) -Note.next =Minitree[preindex].next $Minitree[preindex].next =Note $}

Space is limited, today's blog is first here, the full demo of this blog will still be shared on GitHub, share the address as follows:

GitHub share address:https://github.com/lizelu/DataStruct-Swift/tree/master/Graph

Data structure (v) premium Manaus and Kruskal minimum spanning tree (Swift Object-oriented version)

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.