This question in a real interview? yesexamplegiven graph:a----->b----->C \ | \ | \ | \ v ->d----->Eforreturntrue for return false
Dfs:
1 /**2 * Definition for Directed graph.3 * Class Directedgraphnode {4 * int label;5 * arraylist<directedgraphnode> neighbors;6 * Directedgraphnode (int x) {7 * label = x;8 * Neighbors = new arraylist<directedgraphnode> ();9 * }Ten * }; One */ A Public classSolution { - /** - * @paramgraph:a List of Directed graph node the * @params:the starting Directed graph node - * @paramt:the Terminal Directed Graph node - * @return: A Boolean value - */ + Public BooleanHasroute (arraylist<directedgraphnode>Graph, - Directedgraphnode S, Directedgraphnode t) { + //Write your code here AHashset<directedgraphnode> visited =NewHashset<directedgraphnode>(); at returnDfs (s, T, visited); - } - - Public BooleanDFS (Directedgraphnode s, Directedgraphnode T, hashset<directedgraphnode>visited) { - if(s = = t)return true; - for(Directedgraphnode neighbor:s.neighbors) { in if(!Visited.contains (neighbor)) { - Visited.add (s); to if(Dfs (neighbor, T, visited)) + return true; - } the } * return false; $ }Panax Notoginseng}
BFS:
1 Public classSolution {2 /**3 * @paramgraph:a List of Directed graph node4 * @params:the starting Directed graph node5 * @paramt:the Terminal Directed Graph node6 * @return: A Boolean value7 */8 Public BooleanHasroute (arraylist<directedgraphnode>Graph,9 Directedgraphnode S, Directedgraphnode t) {Ten //Write your code here OneHashset<directedgraphnode> visited =NewHashset<directedgraphnode>(); Alinkedlist<directedgraphnode> queue =NewLinkedlist<directedgraphnode>(); - if(s = = t)return true; - Queue.offer (s); the Visited.add (s); - while(!Queue.isempty ()) { -Directedgraphnode cur =Queue.poll (); - for(Directedgraphnode neighbor:cur.neighbors) { + if(neighbor = = t)return true; - if(Visited.contains (neighbor))Continue; + Visited.add (neighbor); A Queue.offer (neighbor); at } - } - return false; - } -}
Lintcode:route between, Nodes in Graph