Given a directed graph, design an algorithm to find out whether there is a route between two nodes.
Given graph:
A----->B----->C
\ |
\ |
\ |
\ v
->D----->E
for s = B
and t = E
, return true
for s = D
and t = C
, return false
Analysis:
Set + 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 * } 10 * }; 11 */ 12 public class Solution { 13 /** 14 * @param graph: A list of Directed graph node 15 * @param s: the starting Directed graph node 16 * @param t: the terminal Directed graph node 17 * @return: a boolean value 18 */ 19 public boolean hasRoute(ArrayList<DirectedGraphNode> graph, 20 DirectedGraphNode s, DirectedGraphNode t) { 21 Set<DirectedGraphNode> visited = new HashSet<DirectedGraphNode>(); 22 return dfs(graph, s, t, visited); 23 } 24 25 public boolean dfs(ArrayList<DirectedGraphNode> graph, 26 DirectedGraphNode s, DirectedGraphNode t, 27 Set<DirectedGraphNode> visited) { 28 // corner cases 29 if (s == null || t == null) return false; 30 if (s == t) { 31 return true; 32 } else { 33 // flag visited node, avoid cylic 34 visited.add(s); 35 // compare unvisited neighbor nodes recursively 36 if (s.neighbors.size() > 0) { 37 for (DirectedGraphNode node : s.neighbors) { 38 if (visited.contains(node)) continue; 39 if (dfs(graph, node, t, visited)) return true; 40 } 41 } 42 } 43 44 return false; 45 } 46 }