How do I check if a directed graph is acyclic?

后端 未结 11 1776
野的像风
野的像风 2020-11-30 19:16

How do I check if a directed graph is acyclic? And how is the algorithm called? I would appreciate a reference.

11条回答
  •  执念已碎
    2020-11-30 19:40

    here is a swift code to find if a graph has cycles :

    func isCyclic(G : Dictionary>,root : Int , var visited : Array,var breadCrumb : Array)-> Bool
    {
    
        if(breadCrumb[root] == true)
        {
            return true;
        }
    
        if(visited[root] == true)
        {
            return false;
        }
    
        visited[root] = true;
    
        breadCrumb[root] = true;
    
        if(G[root] != nil)
        {
            for child : Int in G[root]!
            {
                if(isCyclic(G,root : child,visited : visited,breadCrumb : breadCrumb))
                {
                    return true;
                }
            }
        }
    
        breadCrumb[root] = false;
        return false;
    }
    
    
    let G = [0:[1,2,3],1:[4,5,6],2:[3,7,6],3:[5,7,8],5:[2]];
    
    var visited = [false,false,false,false,false,false,false,false,false];
    var breadCrumb = [false,false,false,false,false,false,false,false,false];
    
    
    
    
    var isthereCycles = isCyclic(G,root : 0, visited : visited, breadCrumb : breadCrumb)
    

    The idea is like this : a normal dfs algorithm with an array to keep track of visited nodes , and an additional array which serves as a marker for the nodes that led to the current node,so that when ever we execute a dfs for a node we set its corresponding item in the marker array as true ,so that when ever an already visited node encountered we check if its corresponding item in the marker array is true , if its true then its one of the nodes that let to itself (hence a cycle) , and the trick is whenever a dfs of a node returns we set its corresponding marker back to false , so that if we visited it again from another route we don't get fooled .

提交回复
热议问题