如何使用 jgrapht 库标记或着色顶点?

How to label or color a vertex using jgrapht libraries?

我有兴趣使用 jgrapht 提供的各种类型的有向图和无向图 classes 编写图着色算法。 None 他们似乎有能力在图 class 本身(例如 DirectedSimpleGraph)中轻松做到这一点。

我的目标是能够遍历图形对象,add/change 顶点的各种标签或颜色,而不需要将顶点信息存储在对象本身之外 - 即我想使用或创建诸如“DirectedSimpleGraph.setColorToVertex(v, c) 之类的方法,其中 v 是顶点。c 是可能定义为整数的颜色。将不胜感激任何线索或最佳实践建议。

看起来像 jgrapht 库 https://github.com/jgrapht/jgrapht 正在积极开发中。也许你可以联系开发商? 请查看 github link 中的自述文件以获取更多信息。

您可以扩展库中的摘要 类 以添加您想要的自定义字段和函数。

能够为顶点着色或标记的典型方法是将您自己的顶点 class 提供给存储您需要的任何内容的 jgrapht。例如,

public class MyVertex {
  public String colour;
}

SimpleGraph<MyVertex, DefaultEdge> g = 
    new SimpleGraph<MyVertex,DefaultEdge>(DefaultEdge.class);
MyVertex v1 = new MyVertex();
MyVertex v2 = new MyVertex();

g.addVertex(v1);
g.addVertex(v2);

DefaultEdge edge = g.addEdge(v1, v2);

//traverse graph
Graphs.getOppositeVertex(g, edge, v1).colour = "red";

这样,您就不需要使用外部机制(例如哈希映射)来跟踪顶点颜色/标签。

I would like to use or create methods such as "DirectedSimpleGraph.setColorToVertex(v, c), where v is a vertex

图作为一种数据结构没有颜色的概念。只有图形的视觉表示才可以。

因此,您可以使用 DOTExporter 之类的东西以各种方式更改图形,包括为边和顶点着色:

public void printGraph(Graph<GraphNode, DefaultEdge> graph) {
    PrintWriter writer = new PrintWriter(System.out);
    DOTExporter exp = new DOTExporter<>(
            new NodeIdProvider(),
            new NodeLabelProvider(),
            new StringEdgeNameProvider<DefaultEdge>(),
            new NodeAttributeProvider(),
            new EdgeAttributeProvider());
    exp.exportGraph(graph, writer);
}

NodeAttributeProvider 打印每个节点:

public class NodeAttributeProvider implements ComponentAttributeProvider<GraphNode>
{
    @Override
    public Map<String, String> getComponentAttributes(GraphNode component) {
        Map<String, String> attrs = new HashMap<>();
        attrs.put("style", "filled");
        attrs.put("fillcolor", component.getFillColor());
        return attrs;
    }
}

然后您的工作是实现接口 GraphNode 及其方法 getFillColor()