Last active
August 29, 2015 14:03
-
-
Save jingz8804/e9026b3996f265222828 to your computer and use it in GitHub Desktop.
#ctci
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
// 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; | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
line 23: "n1.neighbors" should be "current.neighbors"