Skip to content

Instantly share code, notes, and snippets.

@iwilbert
Created July 13, 2014 21:25
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save iwilbert/fef11bcadca3b1acfa9e to your computer and use it in GitHub Desktop.
Save iwilbert/fef11bcadca3b1acfa9e to your computer and use it in GitHub Desktop.
public boolean isReachable(DirectedGraphNode p, DirectedGraphNode q) {
if (p == null || q == null)
return false;
if (p == q)
return true;
HashSet<DirectedGraphNode> visited = new HashSet<DirectedGraphNode>();
Queue<DirectedGraphNode> queue = new LinkedList<DirectedGraphNode>();
queue.add(p);
visited.add(p);
while (!queue.isEmpty()) {
DirectedGraphNode node = queue.poll();
for (int i = 0; i < node.neighbors.size(); i++) {
DirectedGraphNode nbr = node.neighbors.get(i);
if (nbr == q)
return true;
if (!visited.contains(nbr)) {
queue.add(nbr);
visited.add(nbr);
}
}
}
return false;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment