【问题标题】:Why it is necessary to pass the anc vector by reference in the dfs function?为什么需要在dfs函数中通过引用传递anc向量?
【发布时间】:2021-09-20 04:44:30
【问题描述】:
class Solution
{
    public:
    //Function to detect cycle in a directed graph.
    bool dfs(int V, vector<int> adj[],vector <bool>& isvis,int start,vector<bool>**&**anc)
    {
        isvis[start]=1;
        anc[start]=true;
        for(auto nb : adj[start])
        {   
                
            if(!isvis[nb])
            {
                if(dfs(V,adj,isvis,nb,anc))
                return true;
            }
            
            if(anc[nb]==true)
                return true;
        }
        
        for(int i=0;i<V;i++)
        {
            cout<<i<<" "<<anc[i]<<endl;
        }
        
        anc[start]=false;
        return false;
    }
    bool isCyclic(int V, vector<int> adj[]) 
    {
       vector < bool > isvis(V,false);
       vector <bool> anc(V,false);
       for(int i=0;i<V;i++)
       {
           if(!isvis[i])
           {
               if(dfs(V,adj,isvis,i,anc))
               return true;
           }
       }
       return false;
    }
};

【问题讨论】:

    标签: graph depth-first-search cycle


    【解决方案1】:

    因为函数修改了参数(在anc[start]=true; 中)。如果它是按值传递的,它将拥有自己的向量副本并修改该副本,因此isCyclic 中的anc 变量不会被修改。

    【讨论】:

    • 我们只是用anc向量来跟踪adj的邻居的祖先节点为什么需要修改
    • 而且我没有得到不正确的答案,但我得到了 TLE
    • 再一次,因为你有anc[start]=true;(还有anc[start]=false;接近结尾,递归的dfs调用也会修改ancisvis向量)。
    • 您可以编写一个不这样做的不同实现,然后您可以按值传递anc(但更常见的是通过常量引用传递它以避免复制)。跨度>
    猜你喜欢
    • 2015-05-24
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2023-03-05
    • 1970-01-01
    相关资源
    最近更新 更多