Guava图包:测试无向图是否为树的方法

huangapple go评论110阅读模式
英文:

Guava Graph package: Method for testing if a undirected graph is a tree

问题

我想编写一个函数来测试无向图是否为树。到目前为止,我正在使用以下代码:

Function<Graph<Integer>, Double> targetFunction = g -> {
    boolean isConnected = Graphs.reachableNodes(g, g.nodes().iterator().next()).equals(g.nodes());
    return isConnected && Graphs.hasCycle(g);
};

Guava中是否已经有这个方法的实现(我没有找到)?如果没有,这个实现是否可以改进?

英文:

I want to write a function that tests if a undirected Graph is a tree.
So far, I'm using this:

Function&lt;Graph&lt;Integer&gt;, Double&gt; targetFunction = g -&gt; {
    boolean isConnected = Graphs.reachableNodes(g, g.nodes().iterator().next()).equals(g.nodes());
    return isConnected &amp;&amp; Graphs.hasCycle(g);
};

Is there already an implementation for this method in Guava (didn't find one) and if no, can this be improved?

答案1

得分: 0

你的实现存在两个问题。

  • g.nodes().iterator().next() 返回图中的第一个节点 - 在这个图中是 n1。假设该图是一棵树,n1 可能不是树的根节点。因此,它可达的节点是所有节点的子集。
  • hasCycle 只会检测反向边,而不会检测正向边或交叉边。查看这个答案以了解其中的区别。

我无法从 guava 图形 API 中找到直接的解决方案。它只提供了对图数据结构、广度优先搜索和深度优先搜索的基本支持。

这个问题,确定有向或无向图是否为树,展示了如何实现你想要的算法。

英文:

Your implementation has two problems.

  • g.nodes().iterator().next() returns the first node - n1 in the graph. Assume the graph is a tree, n1 might not be the root of the tree. So its reachable nodes is a subset of all nodes.
  • hasCycle only detect back edges, but not forward edges or cross edges. Check the answer to find out the difference.

I cannot find a direct solution from guava graph api. It only provides basic support for graph data structure, bfs, and dfs.

This question, Determining whether or not a directed or undirected graph is a tree, shows how to implement what the algorithm you want.

huangapple
  • 本文由 发表于 2020年4月6日 21:29:23
  • 转载请务必保留本文链接:https://go.coder-hub.com/61060973.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定