Prim’s algorithm using greedy technique.
Algorithm:
Algorithm prim(E,cost,n,t){
Let (k,l) be an edge of minimum cost in E; mincost :=cost[k,l];
t[l,l]:=k;t[1,2]:=t;
for i:=1 to n do // lnitialize near.
if (cost[i,l] < cost[i,k]) then near[i]:=l; else near[l]:=k;
near[k]:=near[l]:=0; for i:=2 to n-1 do{
Let j be an index such that near[j]!=o and cost[j,near[j]] is minimum;
t[i,l]:=j;t[i,2]:=near[j]; mincost:=mincost+cost[j,near[j]]; near[j]:=0;
for k:=1 to n do // Update near[].
if
(near[k]!=0) and (cost[k,near[k]]>cost[k,j])) then nwar[k] :=j; }
return mincost;}
Source Code:
def prim(E, cost, n, t): S = [t]
T = []
while len(S)
< n:
min_cost = float('inf') for i in S:
for j in range(n):
if j not in S and cost[i][j] < min_cost: min_cost = cost[i][j]
min_edge = (i, j) S.append(min_edge[1]) T.append(min_edge)
return T
E
= [(0, 1), (0, 2), (0, 3), (1, 2), (1, 3), (2, 3)]
|
cost = [[0, |
1, |
3, |
100], |
|
[1, |
0, |
3, |
6], |
|
[3, |
3, |
0, |
4], |
[100, 6, 4, 0]]
n = 4
t = 0
print(prim(E, cost, n, t))
Comments
Post a Comment