C++实现迪杰斯特拉算法

#include 
#include 
#include 

using namespace std;

typedef struct _MGraph
{
	int vertex_num;
	vector> arcs;
}MGraph;

void Dijkstra(MGraph &G, int v0, vector& pathMatrix, vector& shortPathTable)
{
	int v, w, k = 0, min;
	vector final(G.vertex_num);
	pathMatrix.resize(G.vertex_num);
	shortPathTable.resize(G.vertex_num);

	for (v = 0; v < G.vertex_num; v++)
	{
		final[v] = false;
		pathMatrix[v] = 0;
		shortPathTable[v] = G.arcs[v0][v];
	}

	shortPathTable[v0] = 0;
	final[v0] = true;

	for (v = 1; v < G.vertex_num; v++)
	{
		min = INT_MAX;

		for (w = 0; w < G.vertex_num; w++)
		{
			if (!final[w] && shortPathTable[w] < min)
			{
				k = w;
				min = shortPathTable[w];
			}
		}

		final[k] = true;
		for (w = 0; w < G.vertex_num; w++)
		{
			int temp = G.arcs[k][w] == INT_MAX ? INT_MAX : min + G.arcs[k][w];
			if (!final[w] && (temp < shortPathTable[w]))
			{
				shortPathTable[w] = temp;
				pathMatrix[w] = k;
			}
		}
	}
}

int main()
{
	MGraph G;
	G.vertex_num = 6;
	G.arcs = {  {INT_MAX, INT_MAX,      10, INT_MAX,      30,     100},
				{INT_MAX, INT_MAX,       5, INT_MAX, INT_MAX, INT_MAX},
				{INT_MAX, INT_MAX, INT_MAX,      50, INT_MAX, INT_MAX},
				{INT_MAX, INT_MAX, INT_MAX, INT_MAX, INT_MAX,      10}, 
				{INT_MAX, INT_MAX, INT_MAX,      20, INT_MAX,      60},
				{INT_MAX, INT_MAX, INT_MAX, INT_MAX, INT_MAX, INT_MAX}
			 };

	int v0 = 0;
	vector pathMatrix;
	vector shortPathTable;

	Dijkstra(G, v0, pathMatrix, shortPathTable);
	for (auto i : shortPathTable)
		cout << i << " ";
	cout << endl;
	return 0;
}

 

你可能感兴趣的:(数据结构,算法)