All nodes shortest path algorithm Floyd-Warshall

const int INF = 10000;
const int MAX_V = 100;
int cost[MAX_V][MAX_V];
int d[MAX_V][MAX_V];
int _prev[MAX_V][MAX_V]; // 记录A->B的最小路径的B->prev
int V = 7;

const int INF = 10000;
const int MAX_V = 100;
int cost[MAX_V][MAX_V];
int d[MAX_V][MAX_V];
int _prev[MAX_V][MAX_V]; // 记录A->B的最小路径的B->prev
int V = 7;

// 初始化
void init(){
	for(int i = 0; i < V; i++)
		fill(_prev[i], _prev[i] + V, -1);
	
	// 注意,此处初始化花费,例如以下
	// cost[0][1] = 2;
	// cost[0][2] = 5;

	for(int i = 0; i < V; i++){
		for(int j = 0; j < V; j++){
			d[i][j] = cost[i][j];
			if(!d[i][j]){
				if(i == j)
					d[i][j] = 0;
				else
					d[i][j] = INF;
			}
			if(d[i][j] != INF && d[i][j] != 0) // 注意
				_prev[i][j] = i;
		}
	}
}

// 算法
void warshall_floyd(){
	for(int k = 0; k < V; k++){
		for(int i = 0; i < V; i++){
			for(int j = 0; j < V; j++){
				if(d[i][j] > d[i][k] + d[k][j]){
					d[i][j] = d[i][k] + d[k][j];
					_prev[i][j] = _prev[k][j];
				}
			}
		}
	}
}

// 路径输出
void print_path(int s, int e){
	vector<int> path;
	int p = e;
	while(p != -1){
		path.push_back(p);
		p = _prev[s][p];
	}
	reverse(path.begin(), path.end());
	vector<int>::iterator ite = path.begin();
	while(ite != path.end()){
		printf("%d ", *ite);
		ite++;
	}
}

 

Guess you like

Origin blog.csdn.net/ertcmmy/article/details/90713201