Skip to content

Commit 9d7c2dd

Browse files
committed
Fix bug in connectedComponents()
1 parent 86b68f9 commit 9d7c2dd

File tree

2 files changed

+27
-6
lines changed

2 files changed

+27
-6
lines changed

src/main/java/info/debatty/java/graphs/Graph.java

Lines changed: 5 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -200,11 +200,11 @@ public final void prune(final double threshold) {
200200
public final ArrayList<Graph<T>> connectedComponents() {
201201

202202
ArrayList<Graph<T>> subgraphs = new ArrayList<Graph<T>>();
203-
ArrayList<T> nodes_to_process =
204-
new ArrayList<T>(map.keySet());
203+
LinkedList<T> nodes_to_process =
204+
new LinkedList<T>(map.keySet());
205205

206-
for (int i = 0; i < nodes_to_process.size(); i++) {
207-
T n = nodes_to_process.get(i);
206+
while (!nodes_to_process.isEmpty()) {
207+
T n = nodes_to_process.peek();
208208
if (n == null) {
209209
continue;
210210
}
@@ -220,7 +220,7 @@ public final ArrayList<Graph<T>> connectedComponents() {
220220
private void addAndFollow(
221221
final Graph<T> subgraph,
222222
final T node,
223-
final ArrayList<T> nodes_to_process) {
223+
final LinkedList<T> nodes_to_process) {
224224

225225
nodes_to_process.remove(node);
226226

src/test/java/info/debatty/java/graphs/GraphTest.java

Lines changed: 22 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -25,7 +25,6 @@
2525

2626
import info.debatty.java.graphs.build.Brute;
2727
import info.debatty.java.graphs.build.GraphBuilder;
28-
import info.debatty.java.util.BoundedPriorityQueue;
2928
import java.io.BufferedOutputStream;
3029
import java.io.File;
3130
import java.io.FileInputStream;
@@ -76,6 +75,28 @@ public void testConnectedComponents() {
7675
assertEquals(2, graph.connectedComponents().size());
7776
}
7877

78+
/**
79+
* Test the connectedComponents method with isolated nodes (that have no
80+
* neighbors).
81+
*/
82+
public void testConnectedComponentsIsolated() {
83+
System.out.println("Connected components with isolated nodes...");
84+
System.out.println("===========================================");
85+
int k = 10;
86+
Graph<Double> graph = new Graph<Double>(k);
87+
graph.put(15.5, new NeighborList(k));
88+
graph.put(1.55, new NeighborList(k));
89+
graph.put(1.56, new NeighborList(k));
90+
graph.put(1.57, new NeighborList(k));
91+
graph.put(1.58, new NeighborList(k));
92+
graph.put(1.59, new NeighborList(k));
93+
graph.put(1.60, new NeighborList(k));
94+
95+
ArrayList<Graph<Double>> components = graph.connectedComponents();
96+
System.out.println(components);
97+
assertEquals(graph.size(), components.size());
98+
}
99+
79100
/**
80101
* Test of stronglyConnectedComponents method, of class Graph.
81102
*/

0 commit comments

Comments
 (0)