Hello,
I need to change the following code (which contains 3 FOR Loops)
to 1 'WHILE' and '2 FOR loops'. My code, (located in "what have you tried") works but not correct. ¬
I'm getting garbage in some of the edges. I have isolated the problem to the i and k process.
Please help.
Thanks in advance.
Original Code Segment
mstv[source] = true;
edgeWeights[source] = 0;
for (int i = 0; i < gSize - 1; i++)
{
minWeight = DBL_MAX;
for (int j = 0; j < gSize; j++)
if (mstv[j])
for (int k = 0; k < gSize; k++)
if (!mstv[k] && weights[j][k] < minWeight)
{
endVertex = k;
startVertex = j;
minWeight = weights[j][k];
cout << " endVertex K " << endVertex << endl;
cout << " start J " << startVertex << endl;
cout << " minweight " << minWeight << endl;
}
mstv[endVertex] = true;
edges[endVertex] = startVertex;
edgeWeights[endVertex] = minWeight;
} }
The Problem Definition
Write a definition of the new function (Prim2) to implement this algorithm
Input: A connected weighted graph G = (V, E) of N vertices, numbered 0, 1, 2,,,, n-1;
starting with vertex s, with a weight matrix of W.
Output: The minimal spanning tree.
Prim2 (G, W, n, s)
Let T = (V, E), where E = 0
for ( j = 0; j < n; j ++) to n
{
edgeWeights [ j ] = W(s, j);
edges [ j ] = s;
visited [ s ] = false;
}
edgeWeights [ s ] = 0;
visited [ s ] = true
while (not all nodes are visited)
{
Choose the node that is not visited and has the smallest weight, and call it k.
visited [ k ] = true;
E = E U { ( k, edges [ k ] ) }
V = V U { k }
for each node j that is not visited
if (W ( k, j ) < edgeWeights [ j ])
{
edgeWeights [ j ] = W ( k, j );
edges[ j ] = k;
}
return T;
My Code Segment
visited[source] = true; edgeWeights[source] = 0; int i = 0, int k = 0
while (! visited[i] && (k < gSize)) { visited[k] = true; k++;
for (int j = 0; j < gSize; j++) if (weights[k][j] < edgeWeights[j]) {
(edgeWeights[j] = weights[k][j]);
edges[j] = k;
cout << " Edge Weight " <<
edgeWeights[j] << endl; cout << " Edges K " << edges[j] << endl;
} }