Warning: file_get_contents(/data/phpspider/zhask/data//catemap/4/algorithm/12.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Algorithm 检查循环图中组件数量的算法工作不正常_Algorithm_Graph_Depth First Search - Fatal编程技术网

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

Algorithm 检查循环图中组件数量的算法工作不正常,algorithm,graph,depth-first-search,Algorithm,Graph,Depth First Search,我有一个编程问题,我需要计算循环图的组件数量(is图是无向的),因此根据定义,为了检查一个图是否是循环图,检查组件的所有节点是否具有2,就足够了,在下面的代码中,我通过执行深度优先搜索,并通过检查当前组件的每个节点的度是否为2,如果不是,我立即返回false,否则返回true。给定的案例通过,但在提交时,它在测试案例编号18上失败。 请不要介意变量图例 g[] : is a adjacency list graph u : is the current node v : is the chil

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

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 sumof度=0;
bool CanbeCycleutil(矢量[],国际单位,矢量和可视){
如果(g[u].size()!=2)返回0;//此节点没有阶数2,因此该组件不是循环图
vis[u]=1;
对于(int v:g[u])if(而不是vis[v]),返回值可以是cyclutil(g,v,vis);
return 1;//已经遍历了整个组件,并且发现所有节点的阶数都是2,因此这是一个循环图
}
void IsCycle(){
int n,m;
cin>>n>>m;
矢量[n+1];
对于(inti=0;i>x>>y;
g[x]。推回(y);
g[y]。推回(x);
}
向量(n+1,0);
int ans=0;
对于(int i=1;i
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;
}