Minimum spanning Tree-prim algorithm

Source: Internet
Author: User

Prim algorithm is and Kruskal algorithm corresponding to a collision avoidance method, both of the Baidu Encyclopedia are written well, do not repeat

Code
Pascal Code
C code
C + + code
Mathematica Code (below)
Prim[tu_, Dian_]: = module[(* brackets to follow module*) {Diancount=1, (* Point set *) Visit= Table[false, {i,1, Dian}], (* tag has been accessed *) Vall= tu[[1]], (* Initial value *) Pre= table[1, {i,1, Dian}], (* Previous node *) St=1, en =1, val =Infinity, result= Table[infinity, {i,1, Dian}, {J,1, Dian}], (* Final result *) Flag=True, I, J}, visit[[1]] =True; While[diancount!=Dian, Val=Infinity; do[(* Get the smallest side *) If[visit[[i]]==True, continue[]]; If[vall[[i]]< val, en = i; val =Vall[[i]], {i,1, Dian}]; If[val= = Infinity, flag = False; Break[]];(* If all edges are infinite, the illustration is not connected *) St=Pre[[en]]; Result[[st]][[en]]= Val; RESULT[[EN]][[ST]] =Val; Diancount++; Visit[[en]]=True; do[(Update) If[visit[[j]]==True, continue[]]; IF[TU[[EN]][[J]]< VALL[[J] [vall[[j]] =Tu[[en]][[j]]; PRE[[J]]=en], {j,1, Dian}]  ]; If[flag, Return[result], print["Something goes wrong-", Diancount]] ]
Prim
Input:tuer={{inf,7Inf5, INF, INF, INF}, {7Inf8,9,7, INF, INF}, {INF,8, INF, INF,5, INF, INF}, {5,9, INF, INF, the,6, INF}, {INF,7,5,    theInf8,9}, {INF, INF, INF,6,8Inf One}, {inf , INF, INF, INF,9, One, INF}} Prim[tuer,7]output:{{inf,7Inf5, INF, INF, INF}, {7, INF, INF, INF,7, INF, INF }, {inf, INF , INF, INF,5, INF, INF}, {5, INF, INF, INF, INF,6, INF}, {INF,7,5, INF, INF, INF,9}, {INF, INF, INF,6, INF, INF, INF }, {INF, INF, INF, INF ,9, INF, INF}}
View Code (INF is custom infinity)

Minimum spanning Tree-prim algorithm

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.