2016-07-23 2 views
0

나는 지시 된 라벨 그래프를 여러 개의 서브 그래프로 분할해야하는 문제에 대해 작업 중이다. 각 하위 그래프에서 노드는 연결되어 있으며 동일한 레이블을 가지고 있습니다. 이 문제를 해결하는 효율적인 알고리즘이 있습니까?그래프를 버텍스 라벨로 나누기

+2

"파티션"을 정의하십시오. 간단한 DFS를 실행하는 것과 같이 나에게 들리는 것이 문제를 해결할 수 있습니다. –

+0

레이블이 연결된 하나의 꼭지점 집합이 하나의 파티션에 들어갑니다. –

+0

기본적으로 그래프 구성 요소를 찾고 싶습니까? https://en.wikipedia.org/wiki/Connected_component_%28graph_theory%29?wprov=sfla1 –

답변

0

여기 내 솔루션은 Java로 구현되었으며 JGraphT를 그래프 라이브러리로 사용합니다.

private Set<Set<Node>> partition(DirectedGraph<Node, Edge> graph) { 
    Map<Node, Set<Node>> map = new HashMap<Node, Set<Node>>(); 
    for (Edge edge : graph.edgeSet()) { 
     Node source = graph.getEdgeSource(edge); 
     Node target = graph.getEdgeTarget(edge); 
     if (source.getLabel().equals(target.getLabel())) { 
      if (map.get(source) != null && map.get(target) == null) { 
       map.get(source).add(target); 
       map.put(target, map.get(source)); 
      } else if (map.get(target) != null && map.get(source) == null) { 
       map.get(target).add(source); 
       map.put(source, map.get(target)); 
      } else if (map.get(source) == null && map.get(target) == null) { 
       Set<Node> set = new HashSet<Node>(); 
       set.add(source); 
       set.add(target); 
       map.put(source, set); 
       map.put(target, set); 
      } else { 
       Set<Node> sourceSet = map.get(source); 
       Set<Node> targetSet = map.get(target); 
       sourceSet.addAll(targetSet); 
       for(Node n : targetSet){ 
        map.put(n,sourceSet); 
       } 
       targetSet = null; 
      } 
     } else { 
      if (map.get(source) == null) { 
       Set<Node> set = new HashSet<Node>(); 
       set.add(source); 
       map.put(source, set); 
      } 
      if (map.get(target) == null) { 
       Set<Node> set = new HashSet<Node>(); 
       set.add(target); 
       map.put(target, set); 
      } 
     } 
     Collection<Set<Node>> values = map.values(); 
    } 
    return new HashSet<Set<Node>>(map.values()); 
} 
관련 문제