我正在研究Kruskal算法,该算法将读取输入,并基于此信息将找到每两个节点之间的最短路径。
让我解释一下:
输入上有数字,例如:
7 6 1 5
1 7 20
7 2 5
2 3 9
4 2 4
5 2 7
6 5 3
在第一行上有4个数字=节点数,边数,起始节点(起始位置),终止节点(起始位置)。
其余几行是3个数字=一个节点(假设x),第二个节点(y)以及它们之间的长度。
输入将为我提供起点和终点之间的最短路径。
在此示例中,该数字为32。
我有一个可以正常使用的代码:
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
typedef struct edge{
int goal, length;
struct edge *p_next;
} EDGE;
typedef struct node{
int name;
EDGE *p_edges, *last;
} NODE;
int helper;
int getDist(int size, NODE *nodes[size+1], int from, int act, int goal)
{
EDGE *p_act;
for(p_act = nodes[act]->p_edges; p_act != 0; p_act = p_act->p_next)
{
if (p_act->goal == goal)
{
return p_act->length;
}
if (p_act->goal != from)
{
helper = getDist(size, nodes, act, p_act->goal, goal);
}
if (helper != 0)
{
return helper + p_act->length;
}
}
return 0;
}
int main()
{
int numV, numH, start, goal, i, length, a, b;
EDGE *p_newEdge, *p_newEdge2;
scanf("%d %d %d %d", &numV , &numH, &start, &goal);
NODE *nodes [numV+1];
for(i = 0; i <= numV; i++)
{
nodes[i] = (NODE*)malloc(sizeof(NODE));
}
for(i = 0; i < numH; i++)
{
scanf("%d %d %d",&a,&b,&length);
p_newEdge = (EDGE*)malloc(sizeof(EDGE));
p_newEdge->length = length;
p_newEdge->goal = b;
p_newEdge2 = (EDGE*)malloc(sizeof(EDGE));
p_newEdge2->length = length;
p_newEdge2->goal = a;
if (nodes[a]->p_edges == 0)
{
nodes[a]->p_edges = p_newEdge;
nodes[a]->last = p_newEdge;
}
else if (nodes[a]->p_edges != 0)
{
nodes[a]->last->p_next = p_newEdge;
nodes[a]->last = nodes[a]->last->p_next;
}
if (nodes[b]->p_edges != 0)
{
nodes[b]->last->p_next = p_newEdge2;
nodes[b]->last = nodes[b]->last->p_next;
}
else if (nodes[b]->p_edges == 0)
{
nodes[b]->p_edges = p_newEdge2;
nodes[b]->last = p_newEdge2;
}
}
printf("%d\n",getDist(numV ,nodes, 0, start, goal));
return 0;
}
但是我的教授告诉我,这很长,我应该使它更简单(这是我的第三次尝试,对我的教授来说,这仍然太长且“复杂”)。
我不知道如何使其更简单。 有人可以帮我吗?