1. 假设图为无向图,用adjacency matrix表示。Adjacency matrix见Adjacency Matrix -- c++实现
2. 链接的中的程序当两节点为相连时将adjacency matrix中相应元素置1。MST问题中需考虑边的权重,因此连接时矩阵相应元素应设为权重值。
Prim's algorithm见Prim's Algorithm
实现:
void Graph::mstPrim(int v)
{
int *dist = new int[countV];
bool *visited = new bool[countV];
int countVisited = 0; // count the number of visited vertices
for (int i = 0; i < countV; ++i){
dist[i] = 999; // use a large value to initialize the distance array
visited[i] = false; // store the status of each vertex
}
// initialize
dist[v] = 0; // the starting vertex, set its distance to 0
visited[v] = true; // the starting vertex is visited
countVisited = 1;
cout << "MST: " << v << " ";
while (countVisited < countV){
for (int i = 0; i < countV; ++i){
if (visited[i]){
for (int j = 0; j < countV; ++j){
if (adjMat[i][j] != 0 && adjMat[i][j] < dist[j]){
dist[j] = adjMat[i][j];
}
}
}
}
int minDist = 999;
int minIdx;
for (int j = 0; j < countV; ++j){
if (visited[j] == false && dist[j] < minDist){
minDist = dist[j];
minIdx = j;
}
}
visited[minIdx] = true;
cout << "(" << dist[minIdx] << ") " << minIdx << " ";
++countVisited;
}
cout << endl;
delete[] dist;
delete[] visited;
}
测试:
// MST
int start;
cout << "Enter a vertex to start MST:";
cin >> start;
g->mstPrim(start);
测试用图:
结果:
Enter a vertex to start MST:0
MST: 0 (1) 2 (1) 3 (2) 1 (2) 4 (3) 5