Dijkstra shortest path algorithm

The core idea: on the basis of the shortest path has been determined, the shortest path to obtain further vertices.
Each in a cycle:
1. Identify the current from the nearest vertex vk v0 (D array in vk are selected not been determined for all vertices in the shortest path has been determined as the shortest path of vertices and v0. It is already the shortest distance, and it is certainly not change ), and the flag array element subscript k is set to 1;
2. on the basis of the shortest path has been found on the v0 and vk, vk to direct and and not determined vertices adjacent calculated to obtain their current distance and v0, and the D array is corrected .
After the end of a cycle, flag full array of 1, indicating that all vertices have completed the work to find the shortest path, that is the shortest path v0 to any one vertex have been obtained.

Features: For each cycle determined vk, v0 and vk distance is increasing in.

#include<iostream>
using namespace std;
#define MAXVEX 9
#define INFINITY 65536
typedef struct {
	int arc[MAXVEX][MAXVEX];//邻接矩阵
	int numVEXS;//顶点个数
}MGraph;
void ShortestPath_Dijkstra(MGraph&G);
int main() {
	MGraph G;
	G.numVEXS = 9;
	for (int i = 0; i < G.numVEXS; i++)
		for (int j = 0; j < G.numVEXS; j++)
		{
			if (i < j)
				G.arc[i][j] = INFINITY;
			if (i == j)
				G.arc[i][i] = 0;
		}

	G.arc[0][1] = 1; G.arc[0][2] = 5;
	G.arc[1][2] = 3; G.arc[1][3] = 7; G.arc[1][4] = 5;
	G.arc[2][4] = 1; G.arc[2][5] = 7;
	G.arc[3][4] = 2; G.arc[3][6] = 3;
	G.arc[4][5] = 3; G.arc[4][6] = 6; G.arc[4][7] = 9;
	G.arc[5][7] = 5;
	G.arc[6][7] = 2; G.arc[6][8] = 7;
	G.arc[7][8] = 4;
	for (int i = 0; i < G.numVEXS; i++)
		for (int j = 0; j < G.numVEXS; j++)
		{
			if (i < j)
				G.arc[j][i] = G.arc[i][j];
		}

	ShortestPath_Dijkstra(G);

	system("pause");
	return 0;
}

void ShortestPath_Dijkstra(MGraph&G) {
	int k, min;
	int D[MAXVEX] = { 0 }, P[MAXVEX] = { 0 }, flag[MAXVEX] = { 0 };//D[v]表示v0到v的最短路径长度和,final[v]=1表示v0到v的最短路径已经被求出,P数组用来最终确定路径用
	for (int i = 0; i < G.numVEXS; i++)
		D[i] = G.arc[0][i];
	flag[0] = 1;//v0到v0不需要求最短路径

	//start
	for (int n = 1; n < G.numVEXS; n++) {//开始大循环(次数为G.numVEXS-1)
		min = INFINITY;
		for (int i = 0; i < G.numVEXS; i++)
		{
			if (!flag[i] && D[i] < min)
			{
				min = D[i];//找出当前离v0最近的且未被确定的顶点vk
				k = i;//记录下标
			}
		}
		flag[k] = 1;//把顶点vk置为1

		//在已经找到v0与vk的最短路径的基础上,对和vk直接相连的且未被确定的顶点进行计算,得到v0与它们的当前距离
		for (int i = 0; i < G.numVEXS; i++)
		{
			if (!flag[i] && min + G.arc[k][i] < D[i]) //如果找到了更短的路径,则修正D和P
			{
				D[i] = min + G.arc[k][i];
				P[i] = k;//表示vk是vi的前驱
			}

		}
	}
	//打印路径
	while (P[k] != k) {
		cout << P[k] << "-->" << k << endl;
		k = P[k];
	}
}
Published 146 original articles · won praise 3 · Views 4956

Guess you like

Origin blog.csdn.net/ShenHang_/article/details/103927673