Dijkstra's Algorithm for the Cell Shortest Path Problem

Topic content:
There are 5 cities (A, B, C, D, E), where the direct distance from each city to other cities is known, and there is only one road between the two cities. Calculate the shortest path distance from city A to any other city.
enter description
4 rows of data, the first row is the direct distance from A to (B,C,D,E), and the second row is the direct distance from B to (C,D,E). . . , row 4 is the direct distance from D to E.

output description
The shortest distance from city A to (B,C,D,E).

input sample
2 3 4 5  
3 4 2
4 3   
3

Sample output

2 3 4 4


#include <iostream>
using namespace std;


#define INFINITE 0x7fffffff
int PathDijkstra(int cost[5][5], int n, int s, double Dist[], int Pre[]){
	int i, j, k, count;
	int BoolInA [100];
	double mindis;
	int minpnt;
	
	for(i = 0; i < n; i++){
		Dist[i] = cost[s][i];
		Pre[i] = s;
		BoolInA [i] = 0;
	}
	BoolInA [s] = 1;
	for(count = 1; count <= n - 1; count++){
		mindis = INFINITE;
		for(i = 0; i < n; i++){
			if(!BoolInA[i] && mindis > Dist[i]){
				mindis = Dist[i];
				minpnt = i;
			}
		}
		BoolInA [minpnt] = 1;
		for(i = 0; i < n; i++){
			if(!BoolInA[i] && Dist[i] > Dist[minpnt] + cost[minpnt][i]){
				Dist[i] = Dist[minpnt] + cost[minpnt][i];
				Pre[i] = minpnt;
			}
		}
	}
	return 1;
}

int main(){
	int n = 5;
	int cost[5][5], i, j, k;
	double dist[100];
	int pre[100];
	
	for(i = 0; i < n; i++){
		for(j = 1; j < n; j++){
			if(i < j){
				cin >> cost[i][j];
			}else{
				cost[i][j] = INFINITE;
			}
		}
	}
	
//	for(i = 0; i < n; i++){
//		for(j = 0; j < n; j++){
//				cout << cost[i][j] << " ";
//		}
//			cout << endl;
//	}
	
	PathDijkstra (cost, 5, 0, dist, pre);
	for(i = 1; i < n; i++){
		cout << dist[i] << " ";
	}
}




Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=325786587&siteId=291194637