确定初始点为初始前驱
每次遍历前驱为已经被访问的点
后继是已被访问点的相邻未被访问的点
是否被访问用标记数组标记
#include<iostream>
#include<cmath>
#define MaxInt 10000000
#define MVnum 100
using namespace std;
int arcs[6][6] = {0,6,1,5,MaxInt,MaxInt,6,0,5,MaxInt,3,MaxInt,1,5,0,5,6,4,5,MaxInt,5,0,MaxInt,2,MaxInt,3,6,MaxInt,0,6,MaxInt,MaxInt,4,2,6,0
};
bool isFull(bool visited[], int vexnum) {for (int i = 0; i < vexnum; i++) {if (!visited[i]) {return false;}}
}
void prim(bool visited[], int v, int vexnum) {visited[v] = true;while (!isFull(visited, vexnum)) {//当未完全访问,继续访问int temp = MaxInt;int temp_pos_i = 0, temp_pos_j = 0;bool flag = false;for (int i = 0; i < vexnum; i++) {if (visited[i]) {//前驱已经被访问for (int j = 0; j < vexnum; j++) {if (!visited[j] && arcs[i][j] > 0 && arcs[i][j] < temp) {//寻找后继未被访问,边权值大于0,且最小temp = arcs[i][j];temp_pos_i = i;temp_pos_j = j;flag = true;}}}}if (flag) {//后继未被访问,边权值大于0,且最小,输出边visited[temp_pos_j] = true;cout << "加点 " << temp_pos_i + 1 << " 到点 " << temp_pos_j + 1<< "边" << endl;}}
}
int main() {int vexnum = 6, arcnum = 10;bool visited[MVnum] = { false };int v = 1;//访问起点prim(visited, v-1, vexnum);return 0;
}