Week 8 - Greedy Algorithm 2
Week 8 - Greedy Algorithm 2
weighted graph?
What is the shortest distance from one
vertex to another?
Minimum Spanning Tree with
Weighted Graphs
The key activity is to maintain a list of the costs of
links between pairs of nodes.
In this list we repeatedly select the minimum
value.
Priority queue is an appropriate data structure.
Outline of the Algorithm
Start with a vertex, and put it in the tree. Then
repeatedly do the following:
Find all the edges from the newest vertex to
tree.
During the execution of the Algorithm we make
sure that we do not have any edges in the priority
queue that lead to vertices that are already in the
tree.
We could go through the queue looking for and
removing any such edges each time we added a
new vertex to the tree.
The following method creates the minimum
spanning tree for a weighted graph, follows the
algorithm outlined earlier.
public void mstw() {
currentvertex = 0;
while(ntree < nverts – 1) {
vertexlist[currentvertex] .isintree = true;
ntree++;
for(int j = 0; j<nverts; j++){
if(j == currentvertex)
Continue;
if(vertexlist[j].isintree)
continue;
int distance = adjmat[currentvertex][j];
if(distance == infinity)
continue;
putinpq(j, distance);
}
if(thepq.size() == 0){
System.out.println(“Graph not connected”);
return;
}
edge theedge = thepq.removemin();
int sourcevert = the edge.srcvert;
currentvert = theedge.destvert;
System.out.print( vertexlist[sourcevert].abel);
System.out.print(vertexlist[currentvertex].label);
System.out.print(“ “);
}
for(int j=0; j<nverts; j++)
vertexlist[j].isintree = false;
}
The algorithm is carried out in the while loop, which
terminate when all vertices are in the tree.
Within this loop the following activities take place:
The current vertex is placed in the tree.
priority queue.
Edge with the minimum weight is removed from the
priority queue.
The destination vertex of this edge becomes the current
vertex.
The following is the code for putinpq() method:
public void putinpq(int newvert, int newdist) {
int queueindex = thepq.find(newvert);
if(queueindex != -1) {
edge tempedge = thepq.peekn(queueindex);
int olddist = tempedge.distance;
if(olddist > newdist){
thepq.removen(queueindex);
edge theedge = new edge(currentvertex, newvert, newdist);
thepq.insert(theedge);
}
}
else
{
edge theedge = new edge(currentvertex, newvert, newdist);
thepq.insert(theedge);
}}
End of Chapter 8
Any Question?