# Detect Cycle Commented

unknown

plain_text

a year ago

2.8 kB

3

Indexable

Never

^{}

#include <bits/stdc++.h> using namespace std; // vis[node] = 0 means node is not visited // vis[node] = 1 means node is visited in current dfs call // vis[node] = 2 means node is visited in previous dfs call bool dfs(int node, vector<int> &vis, vector<vector<int>> &adj) { // node visited in current dfs call if(vis[node] == 1) return true; // node visited in previous dfs call if(vis[node] == 2) return false; // marking node visited in current dfs call vis[node] = 1; for(int nbr : adj[node]) { if(dfs(nbr, vis, adj)) return true; } // now since we are leaving the dfs call mark it visited in previous dfs call vis[node] = 2; return false; } bool cycleDirectedGraph(int n, vector<vector<int> > &edges){ vector<int> vis(n); vector<vector<int>> adj(n); for(auto i : edges) { adj[i[0]-1].push_back(i[1]-1); } for(int i=0; i<n; ++i) { if(vis[i] == 0) { if(dfs(i, vis, adj)) return true; } } return false; } int main(){ int n,e; cin>>n>>e; vector<vector<int>>edges(e); for (int i = 0; i < e; i++) { int u,v; cin>>u>>v; edges[i].push_back(u); edges[i].push_back(v); } cout<<cycleDirectedGraph(n,edges); return 0; } /* Crio Methodology Milestone 1: Understand the problem clearly 1. Ask questions & clarify the problem statement clearly. 2. Take an example or two to confirm your understanding of the input/output & extend it to test cases Milestone 2: Finalize approach & execution plan 1. Understand what type of problem you are solving. a. Obvious logic, tests ability to convert logic to code b. Figuring out logic c. Knowledge of specific domain or concepts d. Knowledge of specific algorithm e. Mapping real world into abstract concepts/data structures 2. Brainstorm multiple ways to solve the problem and pick one 3. Get to a point where you can explain your approach to a 10 year old 4. Take a stab at the high-level logic & write it down. 5. Try to offload processing to functions & keeping your main code small. Milestone 3: Code by expanding your pseudocode 1. Make sure you name the variables, functions clearly. 2. Avoid constants in your code unless necessary; go for generic functions, you can use examples for your thinking though. 3. Use libraries as much as possible Milestone 4: Prove to the interviewer that your code works with unit tests 1. Make sure you check boundary conditions 2. Time & storage complexity 3. Suggest optimizations if applicable */