# Determining if there is a route between two nodes in a directed graph

This algorithm should return a boolean value, telling if there is a path between two nodes in a given directed graph.

public enum State{
White, Grey;
}

public class Node {
State state = State.White;
List<Node> neighbors = new ArrayList<Node>();
}

public static boolean isThereAPath(Node src, Node dst){
//Assumption: Nodes are initialized with State.White
if(src.state == State.White){
src.state = State.Grey; //Means visiting this node right now
if(node == dst){
return true; //Hit - path found!
}
if(isThereAPath(node, dst))return true;

}
}
return false; //NO path found
}


What do you think about the concept of it? What are the advantages of of an iterative solution?

You don't reset the src.state when you return the result.

This means that between isThereAPath calls you need to reset the state manually. Instead you should reset the state:

public static boolean isThereAPath(Node src, Node dst){
//Assumption: Nodes are initialized with State.White
if(src.state == State.White){
src.state = State.Grey; //Means visiting this node right now
if(node == dst){
src.state = State.White;
return true; //Hit - path found!
}
if(isThereAPath(node, dst)){
src.state = State.White;
return true;
}

}
}
return false; //NO path found
}

• Okay right, If I want to use the structure again afterwards, this is a thing to do. Thanks! – Shady Feb 6 '15 at 8:45

Style: avoid one-liners such as public List<Node>getAdjacent(){ return neighbors;}

• Why? Can you explain your thought process a bit more? – RubberDuck Feb 9 '15 at 3:12
• @RubberDuck I saw style guides (I think it was the Android style guide from Google) where they recommend not doing it because of readability. However, they allow doing one-liners like if(a==b) return a; – Shady Feb 16 '15 at 16:09
• @Shady I'm sorry for the confusion. I was asking barq to expand on his answer. – RubberDuck Feb 16 '15 at 16:11
• It's easier to read if you have the same style for all methods. – barq Feb 16 '15 at 16:18