贝尔曼福特算法 ---- C语言实现

#include<stdio.h>
#include<string.h>
#define MAX 100

typedef struct graph {
int vn;
char vertex[MAX];
int cost[MAX][MAX];
int edge[MAX][MAX];
char route[MAX][MAX];
} GH;

int upde = 1;
int num = 0;

void init(GH *gh);
void bellman_ford(GH *gh);
void update(GH *gh);
void clear(char route[MAX]);
void copy(char sour[MAX],char des[MAX],char appe);
void print(char route[MAX][MAX],int vn);

int main() {
GH grph;
GH *gh = &grph;
char buffer = '\0';
int i = 0,j = 0;
scanf("%d",&grph.vn);
buffer = getchar();
for(i = 0; i < grph.vn; i++) {
	scanf("%c",&grph.vertex[i]);
	buffer = getchar();
}
for(i = 0; i < grph.vn; i++) {
	for(j = 0; j < grph.vn; j++) {
		scanf("%d",&grph.edge[i][j]);
	}
}
for(i = 0; i < grph.vn; i++) {
	for(j = 0; j < grph.vn; j++) {
		scanf("%d",&grph.cost[i][j]);
	}
}
init(gh);
bellman_ford(gh);
printf("总共进行了 %d 次松弛",num - 1);
return 0;
}

void init(GH *gh) {
(*gh).route[0][0] = (*gh).vertex[0];
(*gh).route[0][1] = '\0';
}

void bellman_ford(GH *gh) {
if(upde == 0) {
	print((*gh).route,(*gh).vn);
} else {
	update(gh);
	bellman_ford(gh);
}
}

void update(GH *gh) {
int i = 0,j = 0;
upde = 0;
num++;
for(i = 0; i < (*gh).vn; i++) {
	for(j = 0; j < (*gh).vn; j++) {
		if((*gh).edge[i][j] == 1) {
			if((*gh).cost[0][j] >= (*gh).cost[0][i] + (*gh).cost[i][j]) {
				if((*gh).cost[0][j] > (*gh).cost[0][i] + (*gh).cost[i][j])	upde = 1;
				(*gh).cost[0][j] = (*gh).cost[0][i] + (*gh).cost[i][j];
				clear((*gh).route[j]);
				copy((*gh).route[i],(*gh).route[j],(*gh).vertex[j]);
			}
		}
	}
}
}

void clear(char route[MAX]) {
int i = 0;
for(i = 0; i < MAX; i++) {
	route[i] = '\0';
}
}

void copy(char sour[MAX],char des[MAX],char appe) {
int i = 0;
for(i = 0; i < strlen(sour); i++) {
	des[i] = sour[i];
}
des[i] = appe;
des[i+1] = '\0';
}

void print(char route[MAX][MAX],int vn) {
int i = 0,j = 0;
for(i = 0; i < vn; i++) {
	for(j = 0; j < strlen(route[i]) - 1; j++) {
		printf("%c->",route[i][j]);
	}
	if(i == 0&&j == 0) printf("%c->",route[0][0]);
	printf("%c\n",route[i][strlen(route[i]) - 1]);
}
}
  • 0
    点赞
  • 5
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值