Skip to content

Commit 4614835

Browse files
add support for checking if two nodes are on the same level
1 parent 18837b0 commit 4614835

File tree

2 files changed

+30
-0
lines changed

2 files changed

+30
-0
lines changed

src/main/java/io/github/bldl/graph/ClassHierarchyGraph.java

Lines changed: 20 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -73,6 +73,26 @@ public boolean isDescendant(T ancestor, T descendant, int max_depth) {
7373
return visited.contains(descendant);
7474
}
7575

76+
public boolean sameLevel(T start, T target) {
77+
return isSameLevel(start, target, new HashSet<>(), 0);
78+
}
79+
80+
private boolean isSameLevel(T current, T target, Set<T> visited, int curr_depth) {
81+
if (visited.contains(current))
82+
return false;
83+
if (current.equals(target))
84+
return curr_depth == 0;
85+
visited.add(current);
86+
boolean b = false;
87+
for (T vertex : getOutVertices(current)) {
88+
b = b || isSameLevel(vertex, target, visited, curr_depth + 1);
89+
}
90+
for (T vertex : getInVertices(current)) {
91+
b = b || isSameLevel(vertex, target, visited, curr_depth - 1);
92+
}
93+
return b;
94+
}
95+
7696
private void dfs(T current, Set<T> visited, int max_depth, int curr_depth) {
7797
if (visited.contains(current) || curr_depth >= max_depth && max_depth >= 0)
7898
return;

src/test/java/anthonisen/felix/graph/TestClassHierarchyGraph.java

Lines changed: 10 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -81,4 +81,14 @@ public void testIsDescendant() {
8181
assertTrue(graph.isDescendant(0, 4, -1));
8282
assertFalse(graph.isDescendant(4, 0, -1));
8383
}
84+
85+
@Test
86+
public void testIsSameLevel() {
87+
graph.addEdge(0, 1);
88+
graph.addEdge(0, 2);
89+
graph.addEdge(2, 3);
90+
assertTrue(graph.sameLevel(1, 2));
91+
assertFalse(graph.sameLevel(1, 3));
92+
assertFalse(graph.sameLevel(2, 0));
93+
}
8494
}

0 commit comments

Comments
 (0)