Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- /*
- 0-------------->unvisited
- 1-------------->processing in dfs
- 2-------------->processed
- */
- class Solution {
- bool cycle(int src,map<int,vector<int>> &adj,vector<int> &vis){
- if (vis[src]==1)
- return true;//you came back to ancestor node......cycle here
- vis[src]=1;//make it as processing
- for(auto node:adj[src]){
- if (vis[node]!=2){
- if (cycle(node,adj,vis))
- return true;
- }
- }
- vis[src]=2;//make it as processed
- return false;
- }
- public:
- bool canFinish(int n, vector<vector<int>>& p) {
- vector<int> vis(n,0);
- map<int,vector<int>> adj;
- for(auto x:p)
- adj[x[0]].push_back(x[1]);
- for(int i=0;i<n;++i)
- if (vis[i]==0){
- if (cycle(i,adj,vis))
- return false;
- }
- return true;
- }
- };
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement