图转置使用 Google Guava 图 API

Graph Transpose using Google Guava Graph API

我正在使用 Google Guava Graph API 实现 Kosaraju 的算法,但目前坚持使用标准番石榴 APIs 获得 MutableValueGraph 的转置。

下面是我的代码:

MutableValueGraph<GraphNode,Integer> graph = ValueGraphBuilder.directed()
    .allowsSelfLoops(true)
    .build();

有人可以建议一种将图形转换为其转置并保持底层接口相同的好方法吗 (MutableValueGraph)?有什么办法吗?如果没有,我很乐意更改底层接口。

你应该看看 Graphs helper class, which contains set of transpose methods, specifically Graphs#transpose(ValueGraph)

Returns a view of graph with the direction (if any) of every edge reversed. All other properties remain intact, and further updates to graph will be reflected in the view.

注意返回的视图本身是不可变的(它是 ValueGraph),所以如果你想改变转置图你必须自己复制它的值:

// to obtain a transposed view:
final ValueGraph<String, Integer> transposed = Graphs.transpose(graph); 
// to make a mutable copy of transposed graph:
final MutableValueGraph<String, Integer> transposedMutable = Graphs.copyOf(transposed);