Algorithm for Finding Redundant Edges in a Graph or Tree

前端 未结 6 785
忘掉有多难
忘掉有多难 2020-12-24 08:35

Is there an established algorithm for finding redundant edges in a graph?

For example, I\'d like to find that a->d and a->e are redundant, and then get rid of them,

6条回答
  •  野趣味
    野趣味 (楼主)
    2020-12-24 08:54

    Since the Wikipedia article mentioned by @Craig gives only a hit for an implementation, I post my implementation with Java 8 streams:

    Map> reduction = usages.entrySet().stream()
                    .collect(toMap(
                            Entry::getKey,
                            (Entry> entry) -> {
                                String start = entry.getKey();
                                Set neighbours = entry.getValue();
                                Set visited = new HashSet<>();
                                Queue queue = new LinkedList<>(neighbours);
    
                                while (!queue.isEmpty()) {
                                    String node = queue.remove();
                                    usages.getOrDefault(node, emptySet()).forEach(next -> {
                                        if (next.equals(start)) {
                                            throw new RuntimeException("Cycle detected!");
                                        }
                                        if (visited.add(next)) {
                                            queue.add(next);
                                        }
                                    });
                                }
    
                                return neighbours.stream()
                                        .filter(s -> !visited.contains(s))
                                        .collect(toSet());
                            }
                    ));
    

提交回复
热议问题