Given the edges of a directed graph, and two nodes source and destination of this graph, determine whether or not all paths starting from source eventually end at destination,
this problem is pretty straight forward.
【C++】
class Solution {
public:
bool leadsToDestination(int n, vector<vector<int>>& edges, int source,
int destination) {
vector<bool> visited(n, false);
vector<vector<int>> m(n);
for(auto& e : edges)
m[e[0]].push_back(e[1]);
if(!m[destination].empty()) {return false;}
return dfs(m, source, destination, visited);
}
bool dfs(vector<vector<int>>& m, int cur, int destination,
vector<bool>& visited) {
if (m[cur].size() == 0) {return cur == destination;}
visited[cur] = true;
for(int next : m[cur]) {
if(visited[next] || !dfs(m,next, destination, visited)) {return false;}
}
visited[cur] = false;//回溯
return true;
}
};
【Java】
class Solution {
public boolean leadsToDestination(int n, int[][] edges, int src, int dest) {
Map<Integer, Set<Integer>> graph= new HashMap<>();
for (int i = 0; i < edges.length; ++i) {
graph.putIfAbsent(edges[i][0], new HashSet<Integer>());
graph.get(edges[i][0]).add(edges[i][1]);
}
if (graph.containsKey(dest)) {return false;}
return dfs(graph, src, dest, new boolean[n]);
}
private boolean dfs(Map<Integer, Set<Integer>> graph, int src, int dest,
boolean[] seen) {
if (!graph.containsKey(src)) {return src == dest;}
seen[src] = true;
for (Integer node : graph.get(src)) {
if (seen[node] || !dfs(graph, node, dest, seen)) {
return false;
}
}
seen[src] = false; //backtracking
return true;
}
}