【问题标题】:determine whether an undirected graph is a tree判断无向图是否为树
【发布时间】:2013-01-18 13:35:19
【问题描述】:

我编写了一个算法来确定“无向图是否是树”
假设:图 G 表示为邻接表,其中我们已经知道顶点数为 n

  Is_graph_a_tree(G,1,n) /* using BFS */
    {
      -->Q={1} //is a Queue
      -->An array M[1:n], such that for all i, M[i]=0 /* to mark visited vertices*/
      -->M[1]=1
      -->edgecount=0 // to determine the number of edges visited
      -->While( (Q is not empty) and (edgecount<=n-1) )
        {
            -->i=dequeue(Q)
            -->for each edge (i,j) and M[j] =0 and edgecount<=n-1
               {
                 -->M[j]=1
                 -->Q=Q U {j}
                 -->edgecount++
               }
        }
        If(edgecount != n-1)
            --> print “G is not a tree”
        Else
            {
                -->If there exists i such that M[i]==0 
                        Print “ G is not a tree”
                    Else
                        Print “G is tree”
            }
     }

对吗??
这个算法的时间复杂度是Big0h(n)吗??

【问题讨论】:

    标签: performance time-complexity graph-algorithm


    【解决方案1】:

    我认为边数不正确。您还应该计算女巫 M[j]=1 的边 (i,j),但 j 不是 i 的父节点(因此您还需要保留每个节点的父节点)。 通过将邻接列表的大小相加并除以 2,也许最好在最后计算边数。

    【讨论】:

    • 感谢评论 seviyor..,我认为我们也可以计算 M[j]=1 但条件“edgecount
    • 好吧,我认为任何连接的输入图(即使不是树)的输出都是正确的。
    【解决方案2】:

    你想做一个Depth First Search。无向图只有后边和树边。所以你可以复制 DFS 算法,如果你找到一个后边缘,那么它就不是一棵树。

    【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-06-30
    • 1970-01-01
    • 2019-04-07
    • 1970-01-01
    • 2013-07-03
    • 1970-01-01
    相关资源
    最近更新 更多