墨色风雨
有了一些限制,它可能很容易,没有它可能会变得更复杂。有了约束,我的意思是第一座桥梁应该是真相的来源。想想这些案例:[0,1][1,2][3,4][4,5](内部连接相同长度的两部分)[0,1][1,2][3,4][4,5](第一个桥是排除的)如果桥 1+2 已连接且 3+4 已连接但未将两个部分连接在一起,会发生什么情况?我是说这个...[0,1][2,3][3,4][4,5]假设第一座桥是直通的来源,你可以试试这个:public class IslandConnector { private final List<Bridge> includedBridges = new ArrayList<>(); private List<Bridge> excludedBridges; public IslandConnector(List<Bridge> bridges) { this.excludedBridges = new ArrayList<>(); for(Bridge bridge : bridges) { if(includedBridges.isEmpty()) { includedBridges.add(bridge); } else { if(!tryIncludeBridge(bridge)) { excludedBridges.add(bridge); } } } } private boolean tryIncludeBridge(Bridge bridge) { for(Bridge includedBridge: includedBridges) { if(bridge.hasSameS(includedBridge)) { includeBridge(bridge); return true; } } return false; } private void includeBridge(Bridge bridge) { includedBridges.add(bridge); for(Bridge excludedBridge: excludedBridges) { if(bridge.hasSameS(excludedBridge)) { excludedBridges.remove(excludedBridge); includeBridge(excludedBridge); } } } public List<Bridge> getIncludedBridges() { return includedBridges; } public static void main(String... args) { System.out.println(new IslandConnector(Arrays.asList( new Bridge(0, 1), new Bridge(1, 2), new Bridge(2, 3), new Bridge(3, 4) )).getIncludedBridges()); System.out.println(new IslandConnector(Arrays.asList( new Bridge(0, 1), new Bridge(1, 2), new Bridge(3, 4) )).getIncludedBridges()); System.out.println(new IslandConnector(Arrays.asList( new Bridge(0, 1), new Bridge(2, 3), new Bridge(3, 4) )).getIncludedBridges()); }}印刷[[0,1], [1,2], [2,3], [3,4]][[0,1], [1,2]][[0,1]]
FFIVE
具有以下课程:public class Graph<V> { private static class Edge<VV> { private final VV from; private final VV to; private Edge(VV from, VV to) { this.from = from; this.to = to; } } private final Set<V> vertices = new HashSet<>(); private final Collection<Edge<V>> edges = new ArrayList<>(); public void addEdge(V from, V to) { vertices.add(from); vertices.add(to); edges.add(new Edge(from, to)); } public Set<V> closure(V start) { Set<V> result = new HashSet<>(); closure(start, result); return result; } private void closure(V start, Set<V> seen) { if (vertices.contains(start) && !seen.contains(start)) { seen.add(start); for (Edge<V> e: edges) { if (start.equals(e.from)) { closure(e.to, seen); } } } }}你可以这样做: Graph<Integer> graph = new Graph<>(); graph.addEdge(0,1); graph.addEdge(1,2); graph.addEdge(3,4); int sum = 0; for (int v: graph.closure(0)) { System.out.println("Vertex: " + v); sum += v; } System.out.println("Sum: " + sum);使用以下输出:Vertex: 0Vertex: 1Vertex: 2Sum: 3