简体   繁体   English

将图划分为具有相同 class 的邻居组

[英]Partition graph into groups of neighbours having the same class

Using JGraphT , I would like partition a graph into groups where each group consists of a connected sub-graph of vertices that have the same "class" (denoted using colors below).使用JGraphT ,我想将图形分成组,其中每个组由具有相同“类”的顶点的连接子图组成(在下面使用 colors 表示)。

Example -- the desired groups are in red:示例——所需的组为红色:

在此处输入图像描述

I think this is a rather simple demand and yet I can't find a (built-in) way to do this.我认为这是一个相当简单的需求,但我找不到(内置的)方法来做到这一点。 I notice there is a PartitioningImpl class, that one constructs using a List<Set<V>> classes , yet I don't see a way to use this to partition a graph.我注意到有一个PartitioningImpl class,它使用List<Set<V>> classes构造,但我看不到使用它来划分图形的方法。

Ideally, I'd provide something with my graph and vertex classes (a map of V --> Integer for instance) and it would return something like a List<Set<V>> of partitioned vertex groups.理想情况下,我会为我的图形和顶点类提供一些东西(例如V的 map --> Integer ),它会返回类似于分区顶点组的List<Set<V>>之类的东西。

Sometimes you just cannot avoid writing some code有时你就是无法避免写一些代码

LOOP over classes
   LOOP over nodes that are in class
       Copy node to new graph
   LOOP over edges that connect nodes in class
       Copy edge to new graph
   LOOP over connected components in new graph
       Save component as a group graph for class

This is a fairly simple approach using JGraphT:这是使用 JGraphT 的相当简单的方法:

First remove edges linking neighbouring vertices that belong to different classes and then use ConnectivityInspector on the reduced graph to find connected components , which form the groups.首先删除连接属于不同类的相邻顶点的边,然后在缩减图上使用ConnectivityInspector来查找构成组的连接组件

SimpleGraph<V, E> graph; // given by user
Map<V, Integer> classes; // given by user

List<E> toRemove = new ArrayList<>();
graph.edgeSet().forEach(e -> {
    V a = graph.getEdgeSource(e);
    V b = graph.getEdgeTarget(e);
    if (!classes.get(a).equals(classes.get(b))) {
        toRemove.add(e);
    }
});

graph.removeAllEdges(toRemove);
ConnectivityInspector<V, E> ci = new ConnectivityInspector<>(graph);
List<Set<V>> groups = ci.connectedSets();

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM