Advertisement
nikunjsoni

1059

Jun 22nd, 2021
123
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C++ 0.97 KB | None | 0 0
  1. class Solution {
  2. public:
  3.     const int UNVISITED=1, EXPLORED=2, VISITED=3;
  4.     bool leadsToDestination(int n, vector<vector<int>>& edges, int source, int destination) {
  5.         vector<vector<int>> g(n);
  6.         for(auto edge: edges)
  7.             g[edge[0]].push_back(edge[1]);
  8.    
  9.         vector<int> state(n, UNVISITED);    
  10.         bool cycle = false;
  11.         dfs(source, destination, g, state, cycle);
  12.         return !cycle;
  13.     }
  14.    
  15.     void dfs(int source, int dest, vector<vector<int>> &g, vector<int> &state, bool &cycle){
  16.         if(cycle) return;
  17.         if(state[source] == EXPLORED){
  18.             cycle = true;
  19.             return;
  20.         }
  21.         state[source] = EXPLORED;
  22.         if(!g[source].size() && source != dest){
  23.             cycle = true;
  24.             return;
  25.         }
  26.         for(auto child: g[source])
  27.             if(state[child] != VISITED)
  28.                 dfs(child, dest, g, state, cycle);
  29.         state[source] = VISITED;
  30.     }
  31. };
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement