Dijkstra(迪杰斯特拉)算法

#include
#include

#define Longest_Length 0X0FFFFFF

using namespace std;

int main(){
	//Initialize
	int n, k, start, finish, weight;
	cout << "Please input the number of verticles in the graph:" << endl;
	cin >> n;
	//--------------------Define------------------------
	int **edge = new int *[n + 1];
	int *dis = new int[n + 1];
	bool *visited = new bool[n + 1];
	//--------------------------------------------------
	for(int i = 0; i <= n; i++) dis[i] = Longest_Length;
	for(int i = 0; i <= n; i++) visited[i] = false;
	for(int i = 0; i <= n; i++) edge[i] = new int[n + 1];
	for(int i = 0; i <= n; i++)
		for(int j = 0; j <= n; j++)
			edge[i][j] = Longest_Length;
	//--------------------------------------------------
	cout << "Please input the number of edges in the graph:" << endl;
	cin >> k;
	cout << "Please input the weight of edge with the indexes of its starting point and finishing point:" << endl;
	for(int i = 0; i < k; i++){
		cin >> start >> finish >> weight;
		edge[start][finish] = weight;
	}
	cout << "Please input the starting point:" << endl;
	cin >> start;
	cout << "Please input the finishint point:" << endl;
	cin >> finish;
	//Dijkstra
	int cur = start;
	int *pre = new int[n + 1];
	visited[start] = true;
	dis[start] = 0;
	pre[start] = -1;
	for(int m = 1; m < n; m++){	//find all vertices
		for(int i = 1; i <= n; i++){
			if(!visited[i] && edge[cur][i] < Longest_Length && dis[i] > dis[cur] + edge[cur][i]){
				dis[i] = dis[cur] + edge[cur][i];
				pre[i] = cur;
			}
		}
		int min = Longest_Length, index;
		for(int j = 1; j <= n; j++){
			if(!visited[j] && dis[j] < min){
				min = dis[j];
				index = j;
			}
		}
		cur = index;
		visited[cur] = true;
	}
	cout << "The mininum length is:" << endl;
	cout << dis[finish] << endl;
	cout << "The road is:" << endl;
	for(int i = finish; pre[i] != -1;){
		cout << pre[i] << "->" << i << endl;
		i = pre[i];
	}
	return 0;
}

 

你可能感兴趣的:(算法)