栏目分类:
子分类:
返回
名师互学网用户登录
快速导航关闭
当前搜索
当前分类
子分类
实用工具
热门搜索
名师互学网 > IT > 软件开发 > 后端开发 > C/C++/C#

数据结构 C 代码 7.3: Prim 算法与 Dijkstra 算法

C/C++/C# 更新时间: 发布时间: IT归档 最新发布 模块sitemap 名妆网 法律咨询 聚返吧 英语巴士网 伯小乐 网商动力

数据结构 C 代码 7.3: Prim 算法与 Dijkstra 算法

摘要: 最小生成树算法与单源最短路径算法, 竟然仅差两行代码.

1. 代码

先上代码, 再说废话.

#include 
#include 

#define MAX_DISTANCE 10000


typedef struct Net{
	int** weights;
	int numNodes;
} *NetPtr;


NetPtr initNet(int paraSize, int** paraData) {
	int i, j;
	NetPtr resultPtr = (NetPtr)malloc(sizeof(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];
		}//Of for j
	}//Of for i
	
	return resultPtr;
}//Of initNet


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;
	} // Of for i
	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;
			} // Of if

			if (minDistance > distanceArray[j]) {
				minDistance = distanceArray[j];
				tempBestNode = j;
			} // Of if
		} // Of for 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;
			} // Of if

			// This node cannot be reached.
			if (paraPtr->weights[tempBestNode][j] >= MAX_DISTANCE) {
				continue;
			} // Of if

			// 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;
				} // Of if
			} else {
				if (distanceArray[j] > paraPtr->weights[tempBestNode][j]) {
					// Change the distance.
					distanceArray[j] = paraPtr->weights[tempBestNode][j];
					// Change the parent.
					parentArray[j] = tempBestNode;
				} // Of if
			}//Of if
		} // Of for j
	} // Of for i

	printf("the parent of each node: ");
	for (i = 0; i < numNodes; i++) {
		printf("%d, ", parentArray[i]);
	} // Of for 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]);
		} // Of for i
	} else {
		resultCost = 0;
		for (i = 0; i < numNodes; i++) {
			resultCost += distanceArray[i];
			printf("cost of node %d is %d, total = %drn", i, distanceArray[i], resultCost);
		} // Of for i
		printf("Finally, the total cost is %d.rn ", resultCost);
	}//Of if

	// Step 3. Output for debug.
	printf("rn");

	return resultCost;
}// Of dijkstraOrPrim


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 datarn");
		
	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];
			}//Of if
		}//Of for j
	}//Of for i
 
	printf("Data readyrn");
	
	NetPtr resultNetPtr = initNet(numNodes, tempPtr);
	return resultNetPtr;
}//Of constructSampleNet


void testPrim() {
	NetPtr tempNetPtr = constructSampleNet();
	printf("=====Dijkstra algorithm=====rn");
	dijkstraOrPrim(tempNetPtr, 0);
	printf("=====Prim algorithm=====rn");
	dijkstraOrPrim(tempNetPtr, 1);
}//Of testPrim


int main(){
	testPrim();
	return 1;
}//Of main
2. 运行结果
Preparing data
Data ready
=====Dijkstra algorithm=====
the parent of each node: -1, 0, 0, 0, 2, 2, From node 0, path length to all nodes are: 0 (0), 1 (6), 2 (1), 3 (5), 4 (7), 5 (5),
=====Prim algorithm=====
the parent of each node: -1, 2, 0, 5, 1, 2, cost of node 0 is 0, total = 0
cost of node 1 is 5, total = 5
cost of node 2 is 1, total = 6
cost of node 3 is 2, total = 8
cost of node 4 is 3, total = 11
cost of node 5 is 4, total = 15
Finally, the total cost is 15.

Press any key to continue
3. 代码说明
  1. 图与网络的存储都可以用矩阵. 前者存的是 boolean 值, 后者存的是权值.
  2. Prim 是做最小生成树, 即对应于道路构建; Dijkstra 算法是做单源最短路径, 应用于地图寻径.
  3. O ( n 2 ) O(n^2) O(n2) 的时间复杂度由贪心选择策略, 以及精巧的预处理获得.
  4. 如果用邻接表来做, 速度会更快.
  5. 实际上, 时间复杂度可以优化到 O ( n log ⁡ n ) O(n log n) O(nlogn), 参见 张星移的博客.
转载请注明:文章转载自 www.mshxw.com
本文地址:https://www.mshxw.com/it/937986.html
我们一直用心在做
关于我们 文章归档 网站地图 联系我们

版权所有 (c)2021-2022 MSHXW.COM

ICP备案号:晋ICP备2021003244-6号