【发布时间】:2020-09-25 13:15:29
【问题描述】:
有一个连接顶点的边列表。我正在尝试将这些顶点分成相互连接的组。
static class Edge {
final String from, to;
Edge(String from, String to) {
this.from = from;
this.to = to;
}
}
static Set<String> find(String k, Set<Set<String>> sets) {
for (Set<String> set : sets)
if (set.contains(k))
return set;
return null;
}
static Set<Set<String>> connectedVertices(List<Edge> edges) {
Set<Set<String>> result = new HashSet<>();
for (Edge e : edges) {
Set<String> from = find(e.from, result);
Set<String> to = find(e.to, result);
if (from == null && to == null) {
result.add(new HashSet<>(Set.of(e.from, e.to)));
} else if (from == null) {
to.add(e.from);
} else if (to == null) {
from.add(e.to);
} else if (from != to) {
result.remove(to);
from.addAll(to);
}
}
return result;
}
和
List<Edge> edges = List.of(
new Edge("a", "b"),
new Edge("c", "b"),
new Edge("c", "d"),
new Edge("a", "c"),
new Edge("e", "f"),
new Edge("x", "y"),
new Edge("y", "d"));
System.out.println(connectedVertices(edges));
但结果不是我所期望的。
预期:
[[e, f], [a, b, c, d, x, y]]
实际:
[[a, b, c, d, x, y], [a, b, c, d], [e, f]]
通过以下更改,我得到了我期望的结果,但它很冗长。有没有更好的办法?
static Set<Set<String>> connectedVertices(List<Edge> edges) {
Set<Set<String>> result = new HashSet<>();
for (Edge e : edges) {
Set<String> from = find(e.from, result);
Set<String> to = find(e.to, result);
if (from == null && to == null) {
result.add(new HashSet<>(Set.of(e.from, e.to)));
} else if (from == null) {
result.remove(to);
to.add(e.from);
result.add(to);
} else if (to == null) {
result.remove(from);
from.add(e.to);
result.add(from);
} else if (from != to) {
result.remove(from);
result.remove(to);
from.addAll(to);
result.add(from);
}
}
return result;
}
【问题讨论】: