We use cookies to ensure you have the best browsing experience on our website. Please read our cookie policy for more information about how we use cookies.
/* * Complete the 'countPaths' function below. * * The function accepts following parameters: * 1. INTEGER n * 2. 2D_INTEGER_ARRAY edges */voidcountPaths(intn,vector<vector<int>>edges){constintMOD=1000000000;enumclassColor{White,Gray,// visitingBlack,// visited};vector<vector<int>>g(n+1);for(constauto&e:edges){g[e.front()].push_back(e.back());}vector<Color>color(n+1,Color::White);usingstate_t=std::pair<int,bool>;vector<state_t>paths(n+1);std::function<state_t(int)>dfs;dfs=[&](intv)->state_t{if(v==n){return{1,true};}if(Color::Gray==color[v]){return{-1,false};}if(Color::Black==color[v]){returnpaths[v];}boolcycle=false,found=false;intways=0;color[v]=Color::Gray;for(intu:g[v]){constautostate=dfs(u);found|=state.second;if(state.first<0){cycle=true;}else{ways=(ways+state.first)%MOD;}}ways=cycle&&found?-1:ways;color[v]=Color::Black;paths[v]={ways,found};returnpaths[v];};constautores=dfs(1);if(res.first<0){std::cout<<"INFINITE PATHS"<<std::endl;}else{std::cout<<res.first<<std::endl;}}
Cookie support is required to access HackerRank
Seems like cookies are disabled on this browser, please enable them to open this website
Kingdom Connectivity
You are viewing a single comment's thread. Return to all comments →
I hope this will help someone)