如果图中只有一个周期,如何找到无向图中的顶点周期?

use*_*240 1 c++ algorithm graph-algorithm

如果图中只有一个周期,如何找到无向图中的顶点周期?

我有用于在图中查找循环的代码,但是现在我需要能够找到顶点循环的代码.

这是用于查找周期的代码(在C++中):

bool dfs(int x)
{
    state[x] = 1;
    for(int j = 0; j < ls[x].size(); j++)
    {
        if(state[ls[x][j]] == 1 and parent[x] != ls[x][j])
        {
            t = 0; // Graph contains cycle.
            return t;
        }
        if(state[ls[x][j]] == 0)
        {
            parent[ls[x][j]] = x;
            dfs(ls[x][j]);
        }
    }
}

void detect_cycle()
{
    memset(state, 0, sizeof state);
    memset(parent, 0, sizeof parent);
    for(int i = 1; i <= n; i++)
        if(state[i] == false)
            dfs(i);
}
Run Code Online (Sandbox Code Playgroud)

谢谢.

这是最终的代码.多谢你们.

bool dfs(int x)
{
    state[x] = 1;
    for(int j = 0; j < ls[x].size(); j++)
    {
        if(state[ls[x][j]] == 1 and parent[x] != ls[x][j])
        {
            if(t)
            {
                printf("Cycle entry: %d\n", ls[x][j]);
                printf("Cycle contains: %d, %d ", ls[x][j], x);
                int cycleNode = parent[x];
                while(cycleNode != ls[x][j])
                {
                    printf("%d ", cycleNode);
                    cycleNode = parent[cycleNode];
                }
            }
            t = 0;
            return t;
        }
        if(state[ls[x][j]] == 0)
        {
            parent[ls[x][j]] = x;
            dfs(ls[x][j]);
        }
    }
}
Run Code Online (Sandbox Code Playgroud)

zw3*_*324 5

一个天真的方法 - 只丢掉任何1级节点,直到所有节点都有2级.这是图中的循环.