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
Example
Given graph: A----->B----->C
\ |
\ |
\ |
\ v
->D----->E
for s = B and t = E, return true for s = D and t = C, return false
DFS:
/**
* Definition for Directed graph.
* class DirectedGraphNode {
* int label;
* ArrayList<DirectedGraphNode> neighbors;
* DirectedGraphNode(int x) {
* label = x;
* neighbors = new ArrayList<DirectedGraphNode>();
* }
* };
*/
public class Solution {
/**
* @param graph: A list of Directed graph node
* @param s: the starting Directed graph node
* @param t: the terminal Directed graph node
* @return: a boolean value
*/
public boolean hasRoute(ArrayList<DirectedGraphNode> graph,
DirectedGraphNode s, DirectedGraphNode t) {
// write your code here
HashSet<DirectedGraphNode> visited = new HashSet<DirectedGraphNode>();
visited.add(s);
return dfs(s, t, visited);
} public boolean dfs(DirectedGraphNode s, DirectedGraphNode t, HashSet<DirectedGraphNode> visited) {
if (s == t) return true;
for (DirectedGraphNode neighbor : s.neighbors) {
if (!visited.contains(neighbor)) {
visited.add(s);
if (dfs(neighbor, t, visited))
return true;
}
}
return false;
}
}
BFS:
public class Solution {
/**
* @param graph: A list of Directed graph node
* @param s: the starting Directed graph node
* @param t: the terminal Directed graph node
* @return: a boolean value
*/
public boolean hasRoute(ArrayList<DirectedGraphNode> graph,
DirectedGraphNode s, DirectedGraphNode t) {
// write your code here
HashSet<DirectedGraphNode> visited = new HashSet<DirectedGraphNode>();
LinkedList<DirectedGraphNode> queue = new LinkedList<DirectedGraphNode>();
if (s == t) return true;
queue.offer(s);
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);
queue.offer(neighbor);
}
}
return false;
}
}