Prim算法是和Kruskal算法对应的一个避圈法,两者的百度百科都写得蛮好,不赘述
- 代码
- PASCAL代码
- c代码
- C++代码
- Mathematica代码(如下)
-
Prim[tu_, dian_] := Module[(*中括号要紧跟Module*) {diancount = 1,(*点集*) visit = Table[False, {i, 1, dian}],(*标记是否访问过*) vall = tu[[1]],(*初始取值*) pre = Table[1, {i, 1, dian}],(*前节点*) st = 1, en = 1, val = Infinity, result = Table[Infinity, {i, 1, dian}, {j, 1, dian}],(*最终结果*) flag = True, i, j}, visit[[1]] = True; While[diancount != dian, val = Infinity; Do[(*得到最小的那条边*) If[visit[[i]] == True, Continue[]]; If[vall[[i]] < val, en = i; val = vall[[i]]] , {i, 1, dian} ]; If[val == Infinity, flag = False; Break[]];(*如果所有的边都是无穷,说明图不连通*) st = pre[[en]]; result[[st]][[en]] = val; result[[en]][[st]] = val; diancount++; visit[[en]] = True; Do[(*更新*) 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]] ]
Input: tuer={{INF, 7, INF, 5, INF, INF, INF}, {7, INF, 8, 9, 7, INF, INF}, {INF, 8, INF, INF, 5, INF, INF}, {5, 9, INF, INF, 15, 6, INF}, {INF, 7, 5, 15, INF, 8, 9}, {INF, INF, INF, 6, 8, INF, 11}, {INF, INF, INF, INF, 9, 11, INF}} Prim[tuer, 7] Output: {{INF, 7, INF, 5, 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}}