判断无向图是否是树

发布于 2024-12-19 05:42:21 字数 997 浏览 0 评论 0原文

我编写了一个算法来确定“无向图是否是树”
假设:图 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)吗??

I have written an algorithm to determine "whether an undirected graph is a tree"
Assumptions : graph G is represented as adjacency list, where we already know the number of vertices which is 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”
            }
     }

Is it right??
Is the time complexity of this algorithm Big0h(n)??

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(2

人│生佛魔见 2024-12-26 05:42:21

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

I think the counting of edges is not correct. You should also count edges (i,j) for witch M[j]=1 but j is not the parent of i (so you would also need to keep the parent of each node).
Maybe is better to count the edges at the end, by summing the sizes of the adjacency lists and dividing by 2.

我乃一代侩神 2024-12-26 05:42:21

您想要进行深度优先搜索。无向图只有后边和树边。所以你可以复制 DFS 算法,如果你找到后边缘,那么它就不是一棵树。

You want to do a Depth First Search. An undirected graph has only back edges and tree edges. So you can just copy the DFS algorithm and if you find a back edge then it's not a tree.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文