Skip to content

Instantly share code, notes, and snippets.

@Luoyayu
Last active January 18, 2018 09:11
Show Gist options
  • Save Luoyayu/5bd5a2f0c126d8f60833973ca4b41749 to your computer and use it in GitHub Desktop.
Save Luoyayu/5bd5a2f0c126d8f60833973ca4b41749 to your computer and use it in GitHub Desktop.
find_all_cycle_in_graph_dfs
// 输出图中的所有的环
//color label :white(not visited),black(all children have been visited),gray(start visiting node)
// if one edge direct to a gray node means has cycle.
#include <bits/stdc++.h>
using namespace std;
const int maxn = 1e5+3;
vector<int>g[maxn];
int vis[maxn];//0 while,1 gray, 2 black
int fa[maxn];
void dfs(int u,int father) {
vis[u] = 1;
for (auto v:g[u]) {
if (v == father) continue;
if (!vis[v]) dfs(v, (fa[v] = u));
else if (vis[v] == 1) {
int tmp = u;
while (tmp != v) {
printf("%d->", tmp);
tmp = fa[tmp];
}
printf("%d->%d\n", tmp, u);
}
}
vis[u] = 2;
}
int main() {
int n, m;
scanf("%d%d", &n, &m);
for (int i = 0; i < maxn; i++)
vis[i] = 0, fa[i] = -1, g[i].clear();
for (int i = 0; i < m; i++) {
int u, v;
scanf("%d%d", &u, &v);
g[u].push_back(v);
g[v].push_back(u);
}
int root = 1;
dfs(1,-1); // 连通图
}
/*
* Sample input:
8 9
1 3
3 6
3 7
6 7
1 2
2 4
2 5
5 8
4 8
* Sample output
Cycle: 7->6->3->7
Cycle: 5->8->4->2->5
*/
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment