Path in Directed Graph
https://www.interviewbit.com/old/problems/path-in-directed-graph/
bool dfs(vector<vector<int>> &adj, vector<bool> &visited, int start, int dest){
visited[start] = true;
if(start == dest) return true;
for(int i = 0; i<adj[start].size(); i++){
if(!visited[adj[start][i]]){
if(dfs(adj, visited, adj[start][i], dest)) return true;
}
// return dfs(adj, visited, adj[start][i], dest); -> this is bad
// if recursion is exhausting the call stack (big input case) instead of
// sending the "true" thru the call stack, just check if iteration returns true and
// return true to main fun.
}
return false;
}
int Solution::solve(int A, vector<vector<int>> &B) {
vector<vector<int>> adj(A+1);
for(int i = 0; i<B.size(); i++){
adj[B[i][0]].push_back(B[i][1]); // directed graph
}
vector<bool> visited(A+1, false);
return dfs(adj, visited, 1, A);
}
Comments
Post a Comment