数据结构 Prim 算法与 Dijkstra 算法

话不多说代码如下:

#include <stdio.h>
#include <malloc.h>
 
#define MAX_DISTANCE 10000
 
/**
 * The structure of a Net.
 */
typedef struct Net {
	int** weights;
	int numNodes;
} *NetPtr;
 
/**
 * Initialize a Net.
 */
NetPtr initNet(int paraSize, int** paraData) {
	int i, j;
	NetPtr resultPtr = (NetPtr)malloc(sizeof(struct Net));
	resultPtr->numNodes = paraSize;
	
	//Two stage space allocation.
	resultPtr->weights = (int**)malloc(paraSize * sizeof(int*));
	for (i = 0; i < paraSize; i++) {
		resultPtr->weights[i] = (int*)malloc(paraSize * sizeof(int));
		for (j = 0; j < paraSize; j++) {
			resultPtr->weights[i][j] = paraData[i][j];
		}
	}
	
	return resultPtr;
}
 
/**
 * The Prim algorithm for spanning tree, or the Dijkstra algorithm for nearest path.
 * @param paraAlgorithm 0 for Dijkstra, 1 for Prim
 * @return The total cost of the tree.
 */
int dijkstraOrPrim(NetPtr paraPtr, int paraAlgorithm) {
	int i, j, minDistance, tempBestNode, resultCost;
	int source = 0;
	int numNodes = paraPtr->numNodes;
	int* distanceArray = (int*)malloc(numNodes * sizeof(int));
	int* parentArray = (int*)malloc(numNodes * sizeof(int));
	//Essentially boolean
	int* visitedArray = (int*)malloc(numNodes * sizeof(int));
	
	// Step 1. Initialize. Any node can be the source.
	for (i = 0; i < numNodes; i++) {
		distanceArray[i] = paraPtr->weights[source][i];
		parentArray[i] = source;
		visitedArray[i] = 0;
	}
	distanceArray[source] = 0;
	parentArray[source] = -1;
	visitedArray[source] = 1;
	
	// Step 2. Main loops.
	tempBestNode = -1;
	for (i = 0; i < numNodes - 1; i++) {
		// Step 2.1 Find out the best next node.
		minDistance = MAX_DISTANCE;
		for (j = 0; j < numNodes; j++) {
			// This node is visited.
			if (visitedArray[j]) {
				continue;
			}
			
			if (minDistance > distanceArray[j]) {
				minDistance = distanceArray[j];
				tempBestNode = j;
			}
		}
		
		visitedArray[tempBestNode] = 1;
		
		// Step 2.2 Prepare for the next round.
		for (j = 0; j < numNodes; j++) {
			// This node is visited.
			if (visitedArray[j]) {
				continue;
			}
			
			// This node cannot be reached.
			if (paraPtr->weights[tempBestNode][j] >= MAX_DISTANCE) {
				continue;
			}
			
			// Attention: the difference between Dijkstra and Prim algorithms.
			if (paraAlgorithm == 0) {
				if (distanceArray[j] > distanceArray[tempBestNode] + paraPtr->weights[tempBestNode][j]) {
					// Change the distance.
					distanceArray[j] = distanceArray[tempBestNode] + paraPtr->weights[tempBestNode][j];
					// Change the parent.
					parentArray[j] = tempBestNode;
				} 
			}
			else {
				if (distanceArray[j] > paraPtr->weights[tempBestNode][j]) {
					// Change the distance.
					distanceArray[j] = paraPtr->weights[tempBestNode][j];
					// Change the parent.
					parentArray[j] = tempBestNode;
				}
			}
		}
	}
	
	printf("the parent of each node: ");
	for (i = 0; i < numNodes; i++) {
		printf("%d, ", parentArray[i]);
	}
	
	if (paraAlgorithm == 0) {
		printf("From node 0, path length to all nodes are: ");
		for (i = 0; i < numNodes; i++) {
			printf("%d (%d), ", i, distanceArray[i]);
		}
	}
	else {
		resultCost = 0;
		for (i = 0; i < numNodes; i++) {
			resultCost += distanceArray[i];
			printf("cost of node %d is %d, total = %d\r\n", i, distanceArray[i], resultCost);
		}
		printf("Finally, the total cost is %d.\r\n ", resultCost);
	}
	
	// Step 3. Output for debug.
	printf("\r\n");
	
	return resultCost;
}
 
/**
 * Construct a sample net.
 * Revised from testGraphTranverse().
 */
NetPtr constructSampleNet() {
	int i, j;
	int myGraph[6][6] = {
	{0, 6, 1, 5, 0, 0},
	{6, 0, 5, 0, 3, 0},
	{1, 5, 0, 5, 6, 4},
	{5, 0, 5, 0, 0, 2},
	{0, 3, 6, 0, 0, 6},
	{0, 0, 4, 2, 6, 0} };
	int** tempPtr;
	int numNodes = 6;
	printf("Preparing data\r\n");
	
	tempPtr = (int**)malloc(numNodes * sizeof(int*));
	for (i = 0; i < numNodes; i++) {
		tempPtr[i] = (int*)malloc(numNodes * sizeof(int));
	}//Of for i
	
	for (i = 0; i < numNodes; i++) {
		for (j = 0; j < numNodes; j++) {
			if (myGraph[i][j] == 0) {
				tempPtr[i][j] = MAX_DISTANCE;
			}
			else {
				tempPtr[i][j] = myGraph[i][j];
			}
		}
	}
	
	printf("Data ready\r\n");
	
	NetPtr resultNetPtr = initNet(numNodes, tempPtr);
	return resultNetPtr;
}
 
/**
 * Test the Prim algorithm.
 */
void testPrim() {
	NetPtr tempNetPtr = constructSampleNet();
	printf("=====Dijkstra algorithm=====\r\n");
	dijkstraOrPrim(tempNetPtr, 0);
	printf("=====Prim algorithm=====\r\n");
	dijkstraOrPrim(tempNetPtr, 1);
}
 
/**
 * The entrance.
 */
int main() {
	testPrim();
	return 0;
}

运行结果:在这里插入图片描述
学习总结:
Prim算法和Dijkstra算法是图论中两种非常重要的最短路算法,它们的学习可以帮助我们更好的理解图论基础知识以及算法分析和设计的方法。

  1. Prim算法
    Prim算法是一种贪心算法,用于生成一棵最小生成树。这里的"最小生成树"是指在一个无向图中,选择一些边构造一棵树,使得这棵树的边权值之和最小。Prim算法的基本思想是:从一个起始点开始,每次选择一条未加入最小生成树的最短边,将其加入最小生成树中。这个操作会延伸出一些新的边和点,然后再在这些新的边和点中选择下一条边。直到最后所有的节点都被加入了最小生成树中为止。Prim算法的时间复杂度是O(N^2),N是节点的个数。
  2. Dijkstra算法
    Dijkstra算法也是一种贪心算法,用于寻找一个节点到所有其他节点的最短路。Dijkstra算法的基本思想是:从起始节点开始,对所有节点进行标记,将起始节点标记为0,其他节点标记为正无穷大。然后逐一节点进行松弛操作,直到将所有节点都标记为最短距离为止。松弛操作是指:对于两个节点之间的一条边(起点为u,终点为v),如果经过这条边能够使得v的距离更小,那么就更新v的距离。Dijkstra算法可以解决单源最短路问题,即求一个节点到其他所有节点的最短路。Dijkstra算法的时间复杂度是O(NlogN),N是节点的个数。当使用最小堆作为优先队列时,时间复杂度可以进一步优化到O(MlogN),M是边的个数。
    总结:
    Prim算法和Dijkstra算法都是图论中非常常用的算法,两者都使用贪心算法思想,但解决的问题不同。Prim算法用来找到生成树中的边,Dijkstra算法用来找到单源最短路。在算法实现上,Prim算法常用堆优化,Dijkstra算法常用最小堆。不同的优化方案会影响算法的时间复杂度,需要根据实际情况选择合适的优化方式。
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值