Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- class Solution {
- public:
- const int UNVISITED=1, EXPLORED=2, VISITED=3;
- bool leadsToDestination(int n, vector<vector<int>>& edges, int source, int destination) {
- vector<vector<int>> g(n);
- for(auto edge: edges)
- g[edge[0]].push_back(edge[1]);
- vector<int> state(n, UNVISITED);
- bool cycle = false;
- dfs(source, destination, g, state, cycle);
- return !cycle;
- }
- void dfs(int source, int dest, vector<vector<int>> &g, vector<int> &state, bool &cycle){
- if(cycle) return;
- if(state[source] == EXPLORED){
- cycle = true;
- return;
- }
- state[source] = EXPLORED;
- if(!g[source].size() && source != dest){
- cycle = true;
- return;
- }
- for(auto child: g[source])
- if(state[child] != VISITED)
- dfs(child, dest, g, state, cycle);
- state[source] = VISITED;
- }
- };
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement