Last active
December 12, 2015 02:58
-
-
Save charlespunk/4702749 to your computer and use it in GitHub Desktop.
This file contains hidden or 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
Given a directed graph, design an algorithm to find out whether there is a route between two nodes. |
This file contains hidden or 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
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