Given a directed graph, design an algorithm to find out whether there is a route between two nodes.
Have you met this question in a real interview? Yes ExampleGiven graph:
A----->B----->C \ | \ | \ | \ v ->D----->Efor s = B and t = E, return true
for s = D and t = C, return false
这一到也比较简单,就是考察的递归怎么写,感觉连dfs都不是
代码:
public boolean hasRoute(ArrayList<DirectedGraphNode> graph, DirectedGraphNode s, DirectedGraphNode t) { // write your code here if(graph == null || s == null || t == null) return false; if(s == t) return true; ArrayList<DirectedGraphNode> neighbors = s.neighbors; for(DirectedGraphNode neighbor: neighbors){ if(hasRoute(graph, neighbor, t)){ return true; } } return false; }