Created
July 13, 2014 21:25
-
-
Save iwilbert/fef11bcadca3b1acfa9e to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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