AIZU Online Judge Cycle Detection for a Directed Graph Solution

                     


 Problem Link:  https://judge.u-aizu.ac.jp/onlinejudge/description.jsp?id=GRL_4_A

Solution in C++:

/// La ilaha illellahu muhammadur rasulullah
///******Bismillahir-Rahmanir-Rahim******///
/// Abul Hasnat  Tonmoy
/// Department of CSE,23rd batch
/// Islamic University,Bangladesh
///**********ALLAH IS ALMIGHTY************///
#include <bits/stdc++.h>
using namespace std;
const int N = 1e5 + 9;
std::vector<int> g[N];
bool cycle;
int col[N];
void dfs(int u) {
  col[u] = 1;
  for (auto v : g[u]) {
    if (col[v] == 0) {
      dfs(v);
    } else if (col[v] == 1) {
      cycle = true;
    }
  }
  col[u] = 2;
}
int32_t main() {
  ios_base::sync_with_stdio(0);
  cin.tie(0);
  int n, m;
  cin >> n >> m;
  for (int i = 1; i <= m; i++) {
    int u, v;
    cin >> u >> v;
    g[u].push_back(v);
  }
  cycle = false;
  for (int i = 1; i <= n; i++) {
    if (col[i] == 0) {
      dfs(i);
    }
  }
  cout << cycle << endl;
  return 0;
}

No comments

Most View Post

Recent post

Codeforces Round 971 (Div. 4) 2009C. The Legend of Freya the Frog Solution

  Problem Link    https://codeforces.com/contest/2009/problem/C S olution in C++: /// Author : AH_Tonmoy #include < bits / stdc ++. h ...

Powered by Blogger.