【问题标题】:determining level of n children in breadth first search在广度优先搜索中确定 n 个孩子的级别
【发布时间】:2015-03-27 07:09:30
【问题描述】:

我无法在广度优先搜索程序中确定结束顶点的级别。程序在下面,我给它的任何图形总是将图形中顶点的级别返回为 0。

我猜问题出在函数“级别”,函数如下:

int level(int n,int v,int a[20][20])
{
    int i,j,k,count[20],le[20];
    for(i=1;i<=n;i++)
        count[i]=0;

    for(k=0;k < n;k++)
    {
        for(i=1;i<=n;i++)
        {
            if(count[i]==k)
                for(j=1;j<=n;j++)
                {
                    if(count[j]==0 && a[i][j]==1)
                        count[j]=k+1;
                    else 

                    count[j]=count[j];
                }
        }
    }

    for(i=1;i<=n;i++)
        le[i]=count[i];

    return (*le);
}

我正在尝试返回包含每个顶点级别的数组 le "level",并且我的顶点以数字形式给出。

我的主要功能如下,它工作正常,并给出了图表是否连接:

int main()
{
    int v,w,a[20][20],q[20],visited[20],n,i,j,count=0,le[20];
    printf("\n Enter the number of vertices:");
    scanf("%d",&n);

    for(i=1;i<=n;i++)
    {
        q[i]=0;
        visited[i]=0;
    }

    printf("\n Enter graph data in matrix form:\n");
    for(i=1;i<=n;i++)
        for(j=1;j<=n;j++)
        {
            printf("Is there an edge between (%d,%d)? ",i,j);
            scanf("%d",&a[i][j]);
        }

    printf("\n Enter the starting vertex:");
    scanf("%d",&v);
    printf("\n Enter the ending vertex:");
    scanf("%d",&w);

    bfs(v,a,q,visited,n);
    *le=level(n,v,a);
    count=le[w];

    if(visited[w]==1)
        printf("\nBfs is possible at %d level\n",count);
    else
        printf("\n Bfs is not possible\n");
}

我已将数组作为指针返回。没问题吧?

【问题讨论】:

    标签: c algorithm graph-theory shortest-path


    【解决方案1】:

    您将 le 声明为 int le[20] 并返回 *le。这将返回数组的第一个值。但是lebuffer 的第一个值永远不会设置在级别中。

    不返回数组le 的内容。因此,当您在main 中执行count= le[w] 时,您会在调用level 之前得到le 中的内容。

    le 作为参数传递给level,就像您为a 所做的那样。

    level 中也有这个count[j] = count[j]; 指令。该指令什么也不做。你确定这是你想做的吗?

    在 C 中,数组的索引从 0 到 n-1。您使用从 1 到 n 的范围。它容易出错。例如数组元素buffer[0] 未初始化或设置。你应该坚持 0 到 n-1 的范围。

    【讨论】:

    • 非常感谢!它在删除计数指令并传递 le 后完成
    【解决方案2】:

    我没有完全理解你的代码,但是有什么意义

    count[j]=count[j]; 
    

    ?你能检查一下吗?

    【讨论】:

      猜你喜欢
      • 2013-05-05
      • 1970-01-01
      • 2011-01-31
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2016-02-16
      • 1970-01-01
      相关资源
      最近更新 更多