Skip to content

Instantly share code, notes, and snippets.

@zkytony
Last active November 15, 2015 06:27
Show Gist options
  • Save zkytony/87de2d1917d802fb14df to your computer and use it in GitHub Desktop.
Save zkytony/87de2d1917d802fb14df to your computer and use it in GitHub Desktop.
Java Returns a set of Strings which represent vertices' data at the k-th level from the vertex with given data "start".
/**
* Returns a set of Strings which represent vertices' data at the k-th level from
* the vertex with given data "start". The level is 0 at the given vertex. The level
* increments by 1 when traversal goes one level deeper. For example, consider a graph
* where A has children {B,C}, B has children {D}, C has children {A}. Then when this
* method is called as kthLevelChildren("A", 2), the resulting set would contain
* {A, D}, since these vertices are 2 levels starting from "A".
*
* Note: the purpose of this method is more for testing, in the context of homework 6.
*
* @param start the data of the parent vertex of interest
* @param k the k-th level at which the set of children would be obtained
* @return a set of Strings which represent vertices' data at the k-th level from
* the vertex with given data "start".
* <p>
* Returns null if start == null || k < 0 || this graph does not contain a vertex
* with data "start"; Returns an empty set if there is no children at kth level.
*/
public Set<String> kthLevelChildren(String start, int k) {
if (k < 0 || start == null || !vertexMap.containsKey(start)) {
return null;
} else {
return kthLevelChildren(start, k, new HashSet<String>());
}
}
private Set<String> kthLevelChildren(String start, int k, Set<String> result) {
if (k == 0) {
result.add(start);
return result;
} else {
Set<String> neighbors = neighbors(start);
for (String n : neighbors) {
Set<String> onePath = kthLevelChildren(n, k-1, result);
for (String v : onePath) {
result.add(v);
}
}
return result;
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment