简体   繁体   中英

Detecting a cycle from tree's roots in an undirected graph

i want to determine if a given graph has the structure i want. The structure i want is that if the given graph's tree's roots form a cycle then the output is true, else is false.

Here's an example graph:例如这张图 It has 3 trees and the roots 1,5,4 form a cycle.

Also this is an example that should not pass because it does not contain tree's which root's form a cycle:

图表示例

How can I decide given the vertices which trees should i search?

This is the code so far, printing the adjacency list of a given graph.

#include <iostream>
#include <vector>
using namespace std; 
  
void addEdge(vector<int> vec[], int u, int v) 
{ 
    vec[u].push_back(v); 
} 

void printGraph(vector<int> vec[], int j) 
{
    cout << "Graph's adjacent list: \n";
    for (int v = 0; v < j; ++v) 
    { 
        if (vec[v].size() == 0) continue;
        cout << "Head(" << v << ")"; 
        for (auto x = vec[v].begin(); x != vec[v].end(); x++)
           cout << " -> " << *x; 
        cout << "\n" ; 
    } 
} 

int main() 
{ 
    int V = 10; 
    vector<int> vec[V];
    addEdge(vec, 6, 3); 
    addEdge(vec, 7, 1); 
    addEdge(vec, 8, 9); 
    addEdge(vec, 6, 4); 
    addEdge(vec, 5, 1); 
    addEdge(vec, 1, 9); 
    addEdge(vec, 2, 5); 
    addEdge(vec, 1, 4); 
    addEdge(vec, 5, 4); 
    printGraph(vec, V); 
    return 0; 
} 

Your question is how to tell whether a given graph

  1. contains exactly one cycle,
  2. where each node on the cycle is the root of a tree.

The good news is that, assuming your graph is connected, then if property (1) is true, then so is property (2), To see why this is. imagine deleting any edge from that cycle, Now you have a connected graph with no cycles. which is a tree. That means that every node, not just the ones on the cycle, can then be thought of as the root.

The nice part about this is that there's a really nice algorithm for determining whether a graph is connected and contains exactly one cycle. First, count the number of edges in the graph. If the graph is indeed connected and contains exactly one cycle, then the number of edges should be exactly equal to the number of nodes. (A tree has one more node than edge, and you've added in an edge). If that isn't the case, then stop - the answer is no.

From there, you know you have the right number of nodes and edges. You just need to check whether the graph is connected, and you can do that with a DFS or BFS over the graph.

The nice part about this is that if you implement it correctly, the runtime will be O(n), where n is the number of nodes, independently of the number of edges. After all, if you see more than n edges, you can stop the search.

Hope this helps!

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM