// Iterate N -1 times (since we have initialized dist for vertex 0 already). for (int i = 0; i < N - 1; ++i) { // Find next vertex that not in set, which has smallest distance to existing // set of vertices. int min = INT_MAX; int minIdx = 0; for (int ii = 0; ii < N; ++ii) { if (!minset[ii] && dist[ii] < min) { minIdx = ii; min = dist[ii]; } }
// Add the new vertex to the set, and update all dist accordingly. minset[minIdx] = true; for (int j = 0; j < N; ++j) { if (grid[minIdx][j] && !minset[j] && grid[minIdx][j] < dist[j]) { dist[j] = grid[minIdx][j]; parent[j] = minIdx; } } }
int ret = 0; for (int i = 1; i < N; ++i) { ret += grid[parent[i]][i]; }