最短路之dijkstra算法

最短路问题简常见问题是在一个无向联通图中,给出各个点和边的关系,以及各个边的权值,求出某个点到达其他点的最短路径,本博客是blackcardriver根据dijkstra 经典算法的原理,写出的一个解决最短路问题的模板和思路及分析。供自己复习和分享知识,若有不足或错误之处,望提醒纠正。为迎战六级,注释全部采用英文形式,请多多包涵。欢迎评论。

需要用到的数据结构:

  1. certain_mun ---------//用于记录已算出最短路径的节点的数量。
  2. certain[]-----------------//certain[i]表示节点i是否已被计算出最短路径。
  3. distant[]-----------------//distant[i]表示起点到节点i已发现的最短距离。
  4. edge{node1,node2,val}-----------//表示一个无向边。

大致流程
1.初始化数据,包括初始化 distant[i]certain[i] 等。
2.在未确定找到最短路径的节点中选出一个节点,这个节点的最短路径就是当前distaint值。
更新certain[]. certain_mun,.
3.假设第二步找到的节点名为A,则更新与A相连的所有节点的 distant 值。然后回到第二步,直至
certain_mun 等于重节点数,此事全部节点已经确定了七点到该处的最短路径值。
4.结束

为什么这样?
1.如果一个节点到起点的距离比其他节点都要近,那么不可能通过与其他点作为上一个点得到更短的路径。
2.确定最短路径的点与起点的最短路径依次上升。
3…


以下是我的代码
#include
#include
#include
#include
const int BigInteger = 1e9;
const int maxn = 100;
using namespace std;

int start, n, m;		//start_point, node munber and edge number;
int certain_mun;		//how many node have find the finaly distant value;
bool certain[maxn];		//whether distant[i] is certain to be the shorestest distant
int distant[maxn];		//the distatn from start to node i
int edge[maxn][maxn];	//the distant betweeen two node

void init(){
	memset(certain, 0, sizeof(certain));
	memset(distant, 88, sizeof(distant));	//result is an very big integer mean cant not connect directly
	certain_mun = 0;
	for (int i = 0; i < n; i++){
		distant[i] = min(distant[i], edge[start][i]);
	}
}

void dijkstra(int u){	
	init();
	int nowat = u;
	distant[u] = 0;
	certain[u] = 1;
	certain_mun = 1;
	// find the distant and index of node with shorteset distant with certain[i] equal to 0
	while ( true ){	
		int minn = BigInteger;
		int index;
		for (int i = 0; i < n; i++){
			if ( distant[i] < minn  && certain[i]==0){
				minn = distant[i];
				index = i;
			}
		}
		certain[index] = 1;
		certain_mun++;
		if (certain_mun == n) break;
	//now we can belive that it node have find its final shortest distant,so we uploat other distnat with it distant
		for(int j = 0; j < n; j++){
			if ( certain[j] ) continue;
			distant[j] = min(distant[j], minn + edge[index][j]);
		}
	}
	cout << "-------------------------------------------------" << endl;
	for (int i = 0; i < n; i++){
		printf("%d --> %d  %d \n", start,i, distant[i]);
	}
}

int main(){
	memset(edge, 88, sizeof(edge));
	//node munber , edge munber , and the start point;
	cin >> n >> m >>start;
	for (int i = 0; i < n; i++){
		edge[i][i] = 0;
	}
	//input the data
	for (int i = 0; i < m; i++){
		int a, b, c;
		cin >> a >> b >> c;
		edge[a][b] = edge[b][a] = c;
	}
	dijkstra(start);
	return 0;
}
/* mock-data
6 9 0 
0 1 93
0 4 64 
0 5 6 
1 2 7
2 5 12
2 3 19
3 5 2
3 4 8
4 5 5
*/

结果如下
最短路之dijkstra算法_第1张图片
注意
本代码未经优化,仅仅体现dijkstra算法思想和流程,优化版请到这里:

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