c编写 Shortest Path [4]

4-2 Shortest Path [4]   (10分)

Write a program to find the weighted shortest distances from any vertex to a given source vertex in a digraph. If there is more than one minimum path from v to w, a path with the fewest number of edges is chosen. It is guaranteed that all the weights are positive and such a path is unique for any vertex.

Format of functions:

void ShortestDist( MGraph Graph, int dist[], int path[], Vertex S );

where MGraph is defined as the following:

typedef struct GNode *PtrToGNode;
struct GNode{
    int Nv;
    int Ne;
    WeightType G[MaxVertexNum][MaxVertexNum];
};
typedef PtrToGNode MGraph;

The shortest distance from V to the source S is supposed to be stored in dist[V]. If V cannot be reached from S, store -1 instead. If W is the vertex being visited right before V along the shortest path from S to V, then path[V]=W. If V cannot be reached from Spath[V]=-1, and we have path[S]=-1.

Sample program of judge:

#include <stdio.h>
#include <stdlib.h>

typedef enum {false, true} bool;
#define INFINITY 1000000
#define MaxVertexNum 10  /* maximum number of vertices */
typedef int Vertex;      /* vertices are numbered from 0 to MaxVertexNum-1 */
typedef int WeightType;

typedef struct GNode *PtrToGNode;
struct GNode{
    int Nv;
    int Ne;
    WeightType G[MaxVertexNum][MaxVertexNum];
};
typedef PtrToGNode MGraph;

MGraph ReadG(); /* details omitted */

void ShortestDist( MGraph Graph, int dist[], int path[], Vertex S );

int main()
{
    int dist[MaxVertexNum], path[MaxVertexNum];
    Vertex S, V;
    MGraph G = ReadG();

    scanf("%d", &S);
    ShortestDist( G, dist, path, S );

    for ( V=0; V<G->Nv; V++ )
        printf("%d ", dist[V]);
    printf("\n");
    for ( V=0; V<G->Nv; V++ )
        printf("%d ", path[V]);
    printf("\n");

    return 0;
}

/* Your function will be put here */

Sample Input (for the graph shown in the figure):

8 11
0 4 5
0 7 10
1 7 40
3 0 40
3 1 20
3 2 100
3 7 70
4 7 5
6 2 1
7 5 3
7 2 50
3

Sample Output:

40 20 100 0 45 53 -1 50 
3 3 3 -1 0 7 -1 0





#include <stdio.h>
#include <stdlib.h>




#define INFINITY 1000000
#define MaxVertexNum 10  /* maximum number of vertices */
typedef int Vertex;      /* vertices are numbered from 0 to MaxVertexNum-1 */
typedef int WeightType;
typedef struct GNode *PtrToGNode;
struct GNode{
    int Nv;
    int Ne;
    WeightType G[MaxVertexNum][MaxVertexNum];
};
typedef PtrToGNode MGraph;


MGraph ReadG(); /* details omitted */


void ShortestDist( MGraph Graph, int dist[], int path[], Vertex S );


int main()
{
    int dist[MaxVertexNum], path[MaxVertexNum];
    Vertex S, V;
    MGraph G = ReadG();


    scanf("%d", &S);
    ShortestDist( G, dist, path, S );


    for ( V=0; V<G->Nv; V++ )
        printf("%d ", dist[V]);
    printf("\n");
    for ( V=0; V<G->Nv; V++ )
        printf("%d ", path[V]);
    printf("\n");


    return 0;
}


MGraph ReadG()
{
	MGraph P;
	int i,j,k;
	P=(MGraph)malloc(sizeof(struct GNode));
	scanf("%d%d",&P->Nv,&P->Ne);
	for( j=0;j<MaxVertexNum;j++){
		for( k=0;k<MaxVertexNum;k++){
			P->G[j][k]=-1;
		}
	}
	for( i=0;i<P->Ne;i++){
		int m,n;
		scanf("%d%d",&m,&n);
		scanf("%d",&P->G[m][n]);
	}
	
	return P;
}




/* Your function will be put here */
void ShortestDist( MGraph Graph, int dist[], int path[],Vertex S)
{
	int findmin(MGraph graph,int d[],int know[]);
	int i;
	Vertex known[MaxVertexNum];
	Vertex V,W;
	for(i=0;i<Graph->Nv;i++){
		dist[i]=INFINITY;
		path[i]=-1;
		known[i]=-1;
	}
	dist[S]=0;
	for(;;){
		V=findmin(Graph,dist,known);
		if(V==-1)
			break;
		known[V]=1;
		for(W=0;W<Graph->Nv;W++){
			if(Graph->G[V][W]>0){
					if(dist[V]+Graph->G[V][W]<dist[W]){
						dist[W]=dist[V]+Graph->G[V][W];
						path[W]=V;
					}


			}
		}
	}
	for(i=0;i<Graph->Nv;i++){
		if(dist[i]==INFINITY){
			dist[i]=-1;
			}
	}
}
int findmin(MGraph graph,int d[],int know[])
{
	int i;
	int count=0;
	int min;
	for(min=0;min<graph->Nv;min++){
		if(know[min]==-1)
			break;
	}
	for(i=0;i<graph->Nv;i++){
		if(d[min]>d[i]&&know[i]==-1)
			min=i;
		if(know[i]==1)
			count++;
	}
	if(count!=graph->Nv)
		return min;
	else return -1;
}
好的,以下是使用C语言编写的Dijkstra算法的示例代码。该代码可以处理任意加权图,并且可以通过修改main函数中的输入数据进行测试。 ``` #include <stdio.h> #include <stdlib.h> #include <limits.h> #define MAX_VERTICES 100 #define MAX_EDGES 10000 typedef struct { int u, v, weight; } Edge; void dijkstra(int graph[MAX_VERTICES][MAX_VERTICES], int n, int start, int dist[MAX_VERTICES], int prev[MAX_VERTICES]) { int visited[MAX_VERTICES] = {0}; for (int i = 0; i < n; i++) { dist[i] = INT_MAX; prev[i] = -1; } dist[start] = 0; for (int i = 0; i < n; i++) { int u = -1; for (int j = 0; j < n; j++) { if (!visited[j] && (u == -1 || dist[j] < dist[u])) u = j; } if (dist[u] == INT_MAX) break; visited[u] = 1; for (int v = 0; v < n; v++) { if (graph[u][v] != 0) { int new_dist = dist[u] + graph[u][v]; if (new_dist < dist[v]) { dist[v] = new_dist; prev[v] = u; } } } } } void print_path(int prev[MAX_VERTICES], int start, int end) { if (end == start) printf("%d", start); else if (prev[end] == -1) printf("No path from %d to %d", start, end); else { print_path(prev, start, prev[end]); printf(" -> %d", end); } } int main() { int n, m; int graph[MAX_VERTICES][MAX_VERTICES] = {0}; Edge edges[MAX_EDGES]; printf("Enter the number of vertices: "); scanf("%d", &n); printf("Enter the number of edges: "); scanf("%d", &m); printf("Enter the edges in the format u v weight:\n"); for (int i = 0; i < m; i++) scanf("%d %d %d", &edges[i].u, &edges[i].v, &edges[i].weight); for (int i = 0; i < m; i++) { int u = edges[i].u; int v = edges[i].v; int weight = edges[i].weight; graph[u][v] = weight; graph[v][u] = weight; } int start, end; printf("Enter the start vertex: "); scanf("%d", &start); printf("Enter the end vertex: "); scanf("%d", &end); int dist[MAX_VERTICES]; int prev[MAX_VERTICES]; dijkstra(graph, n, start, dist, prev); printf("Shortest path from %d to %d is: ", start, end); print_path(prev, start, end); printf("\n"); return 0; } ``` 注意:这段代码使用的是邻接矩阵来表示图,如果你使用的是邻接表或其他数据结构来表示图,需要相应地修改代码。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值