检查循环图组件数量的算法无法正常工作

问题描述

我有一个编程问题,我需要计算循环图Cycle Graph definition 的组件数量(is图是无向的)所以根据定义为了检查图是一个循环图,检查组件的所有节点是否都具有 2 度就足够了,在下面的代码中,我通过执行 depth first search 和 for通过检查当前组件的每个节点的度数是否为 2 如果不是,我立即返回 false,否则返回 true。给定的案例通过,但在提交时它在测试案例编号 18 上失败。Problem Source 请不要介意变量图例。

g[] :  is a adjacency list graph
u : is the current node
v : is the child node to be explored
vis[] :  is to check if prevIoUsly node u was visited
n : total number of nodes
m : total number of edges
ans : number of components that are cycle graph

int NofNodes = 0;
int SumOfdegrees = 0;

bool CanbeCycleutil(vector<int>g[],int u,vector<bool>&vis){
    if(g[u].size()!=2) return 0; // this node doesn't have a degree 2,so the component isn't a Cycle graph
    vis[u] = 1;
    for(int v : g[u]) if(not vis[v]) return CanbeCycleutil(g,v,vis);
    return 1; // the entire component has been traversed and all nodes were found to be degree 2,so this one is cycle graph
}

void IsCycle(){
    int n,m;
    cin>>n>>m;
    vector<int>g[n+1];
    for(int i =0;i<m;i++){
        int x,y;
        cin>>x>>y;
        g[x].push_back(y);
        g[y].push_back(x);
    }
    vector<bool>vis(n+1,0);
    int ans = 0;
    for(int i =1;i<=n;i++) if(not vis[i]) ans+=CanbeCycleutil(g,i,vis);  
    cout<<ans;
}

解决方法

暂无找到可以解决该程序问题的有效方法,小编努力寻找整理中!

如果你已经找到好的解决方法,欢迎将解决方案带上本链接一起发送给小编。

小编邮箱:dio#foxmail.com (将#修改为@)