Today we look at prim algorithm. This is also a greedy method. Here we take grow the tree by adding the minimum cost edge that connects to it. That is we look at all the edges that connect to the existing tree and choose the lowest cost.we grow the tree one edge at a time. The algorithm is described as below
Algorithm Prim(E, cost, n, t)
{
Let (k,l) be on edge of minimum cost in E;
t[1,1] = k
t[1,2] = l
mincost = cost[k,l]
for i = 1 to n do
if (cost[i,1] < cost[i,k]) then near[i] = l;
else if cost[i,k] is not large) then near[i] = k
ese near[i] = -1;
near[k] = near[l] = 0;
for ( i = 2 to n-1 ) do
{
Choose j such that near[j] > 0 and cost[j, near[j]] is minimum.
t[i,1] = j; t[i,2] = near[j]; mincost = mincost + cost[j, near[j]]
near[j] = 0;
for k = 1 to n do {
if (near[k] > 0) and (cost[k, near[k]]) > cost[k, j]) or
(near[k] < 0) and (cost[k,j] is not large)
then
near[k] = j;
}
}
return mincost;
}
Algorithm Prim(E, cost, n, t)
{
Let (k,l) be on edge of minimum cost in E;
t[1,1] = k
t[1,2] = l
mincost = cost[k,l]
for i = 1 to n do
if (cost[i,1] < cost[i,k]) then near[i] = l;
else if cost[i,k] is not large) then near[i] = k
ese near[i] = -1;
near[k] = near[l] = 0;
for ( i = 2 to n-1 ) do
{
Choose j such that near[j] > 0 and cost[j, near[j]] is minimum.
t[i,1] = j; t[i,2] = near[j]; mincost = mincost + cost[j, near[j]]
near[j] = 0;
for k = 1 to n do {
if (near[k] > 0) and (cost[k, near[k]]) > cost[k, j]) or
(near[k] < 0) and (cost[k,j] is not large)
then
near[k] = j;
}
}
return mincost;
}
No comments:
Post a Comment