Skip to content

Instantly share code, notes, and snippets.

@jingz8804
Last active August 29, 2015 14:03
Show Gist options
  • Save jingz8804/e9026b3996f265222828 to your computer and use it in GitHub Desktop.
Save jingz8804/e9026b3996f265222828 to your computer and use it in GitHub Desktop.
#ctci
// we can use BFS to check if there is a path between two nodes.
// Assume that we have a Node class as follows:
// public class Node{
// boolean isVisited = false;
// ArrayList<Node> neighbors = new ArrayList<Node>();
// }
// if the Node class does not have a boolean attribute to indicate whether it has been visited or not,
// we can always create a wrapper class that wrap a Node and a boolean variable
import java.util.Queue;
import java.util.LinkedList;
public class PathBetweenNodes{
public boolean hasPath(Node n1, Node n2){
if(n1 == null || n2 == null) return false;
Queue<Node> queue = new LinkedList<Node>();
queue.offer(n1);
n1.isVisited = true;
Node current = null;
while(!queue.isEmpty()){
current = queue.poll();
if(current == n2) return true;
for(Node neighbor: n1.neighbors){
if(!neighbor.isVisited){
queue.offer(neighbor);
neighbor.isVisited = true;
}
}
}
return false;
}
}
@diegozeng
Copy link

line 23: "n1.neighbors" should be "current.neighbors"

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment