c_cpp find_all_cycle_in_graph_dfs

Posted

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了c_cpp 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 father[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, father[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
 
*/

以上是关于c_cpp find_all_cycle_in_graph_dfs的主要内容,如果未能解决你的问题,请参考以下文章

c_cpp 127.单词阶梯

c_cpp MOFSET

c_cpp MOFSET

c_cpp 31.下一个排列

c_cpp string→char *

c_cpp 54.螺旋矩阵