C语言实现Dijkstra算法

题目实例:
给一个n(1 ≤ n ≤ 2500) 个点 m(1 ≤ m ≤ 6200) 条边的无向图,求 s 到 t 的最短路。

输入格式:
第一行四个由空格隔开的整数 n、m、s、t。

之后的 m 行,每行三个正整数 si​、ti​、wi​(1≤wi​≤109),表示一条从si​ 到 ti​ 长度为 wi​ 的边。

输出格式:
一个整数,表示从s 到t 的最短路径长度。数据保证至少存在一条道路。

输入样例:
7 11 5 4
2 4 2
1 4 3
7 2 2
3 4 3
5 7 5
7 3 3
6 1 1
6 3 4
2 4 3
5 6 3
7 2 1
结尾无空行

输出样例:
7
 

#define _CRT_SECURE_NO_WARNINGS
#include<stdio.h>
#include<stdlib.h>
#define INFINITY  65535
#define MaxVertexNum 2500
int dist[MaxVertexNum], path[MaxVertexNum]
, collected[MaxVertexNum];
int s, t;
typedef struct GNode* PtrToGNode;
struct GNode {
	int Nv;
	int Ne;
	int G[MaxVertexNum][MaxVertexNum];
};
typedef PtrToGNode MGraph;
typedef struct ENode* PtrToENode;
struct ENode {
	int V1, V2;
	int Weight;
};
typedef PtrToENode Edge;
MGraph CreateGraph(int VertexNum) {
	int V, W;
	MGraph Graph;
	Graph = (MGraph)malloc(sizeof(struct GNode));
	Graph->Nv = VertexNum;
	Graph->Ne = 0;
	for (V = 1; V <= Graph->Nv; V++)
		for (W = 1; W <= Graph->Nv; W++)
			Graph->G[V][W] = INFINITY;
	return Graph;
}
void InsertEdge(MGraph Graph, Edge E) {
	Graph->G[E->V1][E->V2] = E->Weight;
	Graph->G[E->V2][E->V1] = E->Weight;
}
MGraph BuildGraph() {
	MGraph Graph;
	Edge E;
	int V,Nv,i;
	scanf("%d", &Nv);
	Graph = CreateGraph(Nv);
	scanf("%d", &(Graph->Ne));
	scanf("%d%d", &s, &t);
	if (Graph->Ne != 0) {
		E = (Edge)malloc(sizeof(struct ENode));
		for (i = 0; i < Graph->Ne; i++) {
			scanf("%d%d%d", &E->V1, &E->V2, &E->Weight);
			InsertEdge(Graph, E);
		}
	}
	return Graph;
}
int FindMinDist(MGraph Graph, int dist[], int collected[]) {
	int MinV, V;
	int MinDist = INFINITY;
	for(V = 1; V <= Graph->Nv; V++) {
		if (collected[V] == false && dist[V] < MinDist) {
			MinDist = dist[V];
			MinV = V;
		}
	}
	if (MinDist < INFINITY)
		return MinV;
	else return -1;
}
bool Dijkstra(MGraph Graph, int dist[], int path[], int S) {
	int V, W;
	for (V = 1; V <= Graph->Nv; V++) {
		dist[V] = Graph->G[S][V];
		if (dist[V] < INFINITY)
			path[V] = S;
		else
			path[V] = -1;
		collected[V] = false;
	}
	dist[S] = 0;
	collected[V] = true;
	while (1) {
		V = FindMinDist(Graph, dist, collected);
		if (V == -1)
			break;
		collected[V] = true;
		for(W=1;W<=Graph->Nv;W++)
			if (collected[W] == false && Graph->G[V][W] < INFINITY) {
				if (Graph->G[V][W] < 0)
					return false;
				if (dist[V] + Graph->G[V][W] < dist[W]) {
					dist[W] = dist[V] + Graph->G[V][W];
					path[W] = V;
				}
			}
	}
	return true;
}
int main() {
	MGraph Graph = BuildGraph();
	Dijkstra(Graph, dist, path, s);
	printf("%d", dist[t]);
	return 0;
}

  • 0
    点赞
  • 3
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值