分段故障核心转储在Kruskal算法

问题描述:

#include<stdio.h> 

int find(int, int parent[10]); 

int uni(int, int, int parent[10]); 

int main() 
{ 
    int i, j, k, a, b, u, v, n, ne = 1; 
    int min, mincost = 0, cost[9][9], parent[9]; 
    printf("\n\tImplementation of Kruskal's algorithm\n"); 
    printf("\nEnter the no. of vertices:"); 
    scanf("%d", &n); 
    printf("\nEnter the cost matrix:\n"); 

    for (i = 1; i <= n; i++) 
    { 
     for (j = 1; j <= n; j++) 
     { 
      printf("Enter the cost of the edge(%d,%d)=", i, j); 
      scanf("%d", &cost[i][j]); 

      if (cost[i][j] == 0) 
      { 
       cost[i][j] = 999; 
      } 
     } 
    } 

    printf("The edges of Minimum Cost Spanning Tree are\n"); 

    while (ne < n) 
    { 
     for (i = 1, min = 999; i <= n; i++) 
     { 
      for (j = 1; j <= n; j++) 
      { 
       if (cost[i][j] < min) 
       { 
        min = cost[i][j]; 
        a = u = i; 
        b = v = j; 
       } 
      } 
     } 

     u = find(u, parent); 
     v = find(v, parent); 

     if (uni(u, v, parent) == 1) 
     { 
      printf("%d edge (%d,%d) =%d\n", ne++, a, b, min); 
      mincost += min; 
     } 

     cost[a][b] = cost[b][a] = 999; 
    } 

    printf("\n\tMinimum cost = %d\n", mincost); 

} 

int uni(int i, int j, int parent[10]) 
{ 
    if (i != j) 
    { 
     parent[j] = i; 
     return 1; 
    } 

    return 0; 
} 

int find(int i, int parent[10]) 
{ 
    while (parent[i]) 
    { 
     i = parent[i]; 
    } 

    return i; 
} 

这是无法计算U,V,单...我能够进入值,但我得到一个消息分段错误(核心转储)。我猜有一些问题,函数find和uni(可能在传递数组父项)..分段故障核心转储在Kruskal算法

+0

你知道哪里有错误发生? – 2015-02-06 10:20:41

+0

就是这样,就你而言?没有运行调试器,甚至没有添加printf()来检查发生了什么,或者在哪个*特定的值下程序失败?没有检查'scanf()的返回值,没有镜像程序读取的内容?没有'assert()'? – DevSolar 2015-02-06 10:21:56

+0

所有未检查scanf结果的代码都应该通过计算器自动拒绝并发送相应的消息。 :-) – Jens 2015-02-06 10:34:11

没有试图破译代码实际上是什么(单字母变量,零注释,没有链接这个“Kruskal算法”或任何其他内容),除了我在我的评论中已经写入的有关添加printf()s来记录中间值,检查scanf()返回代码,将用户输入镜像回用户以及将代码与assert()s一起喷洒的信息之外。 ..

int parent[9]已声明,但尚未初始化。 find()使用(未初始化的)内容。未定义的行为就在那里。

各种“腥”的细节,如main()宣布parent[9]cost[9][9],但函数声明parent[10]。您还让用户输入顶点数量,但愉快地假定当您使用该数字作为上限循环界限时,它不会超过9。如果您对提供的存储容量的假设不成立,则您正在查看超出边界的访问。

此时代码审查我折腾下来的代码打印在桌子上,给你的那些长期,艰苦的目光一...

+0

感谢所有人解决了它..问题是父母数组传递给父母[10],而不是初始化它.. – user2867280 2015-02-06 19:05:37