Skip to content

Instantly share code, notes, and snippets.

@charlespunk
Last active December 12, 2015 02:58
Show Gist options
  • Save charlespunk/4702749 to your computer and use it in GitHub Desktop.
Save charlespunk/4702749 to your computer and use it in GitHub Desktop.
Given a directed graph, design an algorithm to find out whether there is a route between two nodes.
class Node{
LinkedList<Node> sons;
int state; //0 for unvisited, 1 for visited
}
public boolean hasRoute(Node begin, Node end){
if(begin == null || end == null) return false;
if(begin == end) return true;
LinkedList<Node> q = new LinkedList<>();
begin.state = 1;
q.add(begin);
while(!q.isEmpty()){
Node thisNode = q.removeFirst();
for(Node nextNode : q.sons){
if(next.state == 0){
if(next == end) return true;
else{
next.state = 1;
q.add(next);
}
}
}
}
return false;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment