考研数据结构-最短路径

迪杰特斯拉(Dijkstra)

void Dijkstra(MGraph *G, int v, int dist[], int path[])
{
	int i, j, min, now, set[maxSize] = {0};
	
	for(i = 0; i < G->n; i++)
	{
		if(G->edges[v][i] < Inf)
			path[i] = v;
		else
			path[i] = -1;
		dist[i] = G->edges[v][i];
	}
	
	set[v]  =  1;
	path[v] = -1;
	dist[v] =  0;
	
	for(i = 0; i < G->n-1; i++)
	{
		min = Inf;
		
		for(j = 0; j < G->n; j++)
			if(set[j] == 0 && dist[j] < min)
			{
				now = j;
				min = dist[j];
			}
			
		set[now] = 1;
		
		for(j = 0; j < G->n; j++)
			if(set[j] == 0 && dist[now]+G->edges[now][j]  < dist[j])
			{
				dist[j] = dist[now]+G->edges[now][j];
				path[j] = now;
			}
	}
}

弗洛伊德(Floyd)

void Floyd(MGraph *G, int path[][maxSize])
{
	int i, j, k, dist[maxSize][maxSize];
	
	for(i = 0; i < G->n; i++)
		for(j = 0; j < G->n; j++)
		{
			dist[i][j] = G->edges[i][j];
			path[i][j] = -1;
		}
		
	for(k = 0; k < G->n; k++)
		for(i = 0; i < G->n; i++)
			for(j = 0; j < G->n; j++)
				if(dist[i][k]+dist[k][j] < dist[i][j])
				{
					dist[i][j] = dist[i][k]+dist[k][j];
					path[i][j] = k;
				}
}

你可能感兴趣的:(考研)