Minimum Spanning Tree (MST) -- Prim's Algorithm (c++实现)

3 篇文章 0 订阅

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


  • 0
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值