簡體   English   中英

將圖划分為具有相同 class 的鄰居組

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

使用JGraphT ,我想將圖形分成組,其中每個組由具有相同“類”的頂點的連接子圖組成(在下面使用 colors 表示)。

示例——所需的組為紅色:

在此處輸入圖像描述

我認為這是一個相當簡單的需求,但我找不到(內置的)方法來做到這一點。 我注意到有一個PartitioningImpl class,它使用List<Set<V>> classes構造,但我看不到使用它來划分圖形的方法。

理想情況下,我會為我的圖形和頂點類提供一些東西(例如V的 map --> Integer ),它會返回類似於分區頂點組的List<Set<V>>之類的東西。

有時你就是無法避免寫一些代碼

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

這是使用 JGraphT 的相當簡單的方法:

首先刪除連接屬於不同類的相鄰頂點的邊,然后在縮減圖上使用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