这是我的代码。这将使用户的信息很好,但它不会调用prims! (它甚至不会在通话前打印语句..)。问题是,这个main()只是使用kruskals而不是prims从这个问题的尝试中复制和粘贴..主要没有改变,它曾经工作正常,唯一的区别是prims()现在有。我看不出任何理由为什么程序会停止(然后什么也不做。闪烁光标没什么)。发生了什么事?
#include <stdio.h>
#include <stdlib.h>
#include <math.h>
#define MAX 50
typedef struct graph{
int vertices;
int edges;
int vertex[MAX];
int edge[MAX][4]; /*[i][0]=i (edge ref) [i][1]=vertex1 [i][2]=vertex2 [i][3]=weight*/
} Graph;
void prims(Graph graph);
int main () {
Graph* graph=malloc(sizeof *graph);
printf("Please enter the number of vertices in your graph: ");
scanf("%i", &graph->vertices);
printf("\nPlease enter the number of edges in your graph: ");
scanf("%i", &graph->edges);
for (int i=0; i<graph->edges; ++i) {
graph->edge[i][0]=i;
ensure_valid_input:
printf("\nPlease enter the vertices connected by edge %i, and its weight: ",i+1);
scanf("%i %i %i", &graph->edge[i][1], &graph->edge[i][2], &graph->edge[i][3]);
if (graph->edge[i][1]>graph->vertices || graph->edge[i][2]>graph->vertices || graph->edge[i][1] <= 0 || graph->edge[i][2] <= 0) {
printf("\nERROR: One of these vertices is invalid; ensure they are both in range 1 - %d\n", graph->vertices);
goto ensure_valid_input;
}
}
printf("Try to call the function?");
prims(*graph);
/*Print result to screen*/
/*Print result to file*/
return 0;
}
void prims(Graph graph){
printf("Function called...");
/*Initialise sets and test-values*/
int edges_ordered[graph.edges];
int used_vertices[graph.vertices];
int used_edges[graph.vertices-1];
int least_avail_edge;
int least_edge_reset;
int existing_entry;
int done=1;
int vertex_present;
for (int i=0; i<graph.vertices; ++i) {
if (i=0) {
used_vertices[i]=0;
}
else {
used_vertices[i]=-1;
}
}
/*Order the edges*/
for (int i=0; i<graph.edges; ++i) {
least_avail_edge = least_edge_reset;
existing_entry = 1;
for (int j=0; j<graph.edges; ++j) {
if (graph.edge[j][3]<=graph.edge[least_avail_edge][3]) {
for (int k=0; k<graph.edges; ++k) {
if (edges_ordered[k]==graph.edge[j][0]) {
existing_entry=0;
}
}
if (existing_entry==1) {
least_avail_edge=j;
}
}
}
edges_ordered[i]=least_avail_edge;
}
//Diagnotstic Print
for (int i=0; i<graph.edges; ++i) {
printf("\n%d) Edge %d, Weight %d\n)", i+1, edges_ordered[i]+1, graph.edge[i][3]);
}
/*Continually add next appropriate edge to tree until spanning*/
while (done!=0) {
/*Test to see if all vertices are in the tree yet*/
done=0;
for (int i=0; i<graph.vertices; ++i) {
vertex_present=1;
for (int j=0; j<graph.vertices; ++j) {
if (graph.vertex[i]==used_vertices[j]) {
vertex_present=0;
}
}
if (vertex_present==1) {
/*Vertex is missing from tree -- not done!*/
done=1;
break;
}
}
}
}
答案 0 :(得分:3)
此代码存在很多问题,但我怀疑罪魁祸首在prims()
函数中:
if (i=0) {
我认为你的意思是==
。您每次循环都将i
设置为零,这会导致循环永不终止,冻结您的程序。
其他问题是least_edge_reset
未初始化,malloc
的返回值未被强制转换(取决于C / C ++版本和编译器设置,您是否会收到错误或警告) ,sizeof *graph
很尴尬。此外,没有防止超过最大边数等的保护,但我会停在那里,因为它不是你所问的。
我怀疑你的print
语句正在运行,但由于没有\n
,它正在被缓冲而不会立即显示在屏幕上,因为prims()
被卡住而永远不会显示在无限循环中。