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

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 中实现了此方法(未找到),如果没有,是否可以改进?

您的实施有两个问题。

  • g.nodes().iterator().next() returns 图中的第一个节点 - n1。假设图是一棵树,n1 可能不是树的根。所以它的可达节点是所有节点的子集。
  • hasCycle只检测后向边缘,不检测前向边缘或交叉边缘。检查 the answer 以找出差异。

我无法从番石榴图中找到直接的解决方案 api。仅对图数据结构、bfs、dfs提供基础支持

这个问题,Determining whether or not a directed or undirected graph is a tree,展示了如何实现你想要的算法。