Skip to content

Instantly share code, notes, and snippets.

@csullivan
Last active September 11, 2016 20:38
Show Gist options
  • Save csullivan/e704a69223ab56c502a8c87c6fc6c0f3 to your computer and use it in GitHub Desktop.
Save csullivan/e704a69223ab56c502a8c87c6fc6c0f3 to your computer and use it in GitHub Desktop.
S - Set of all nodes with no inbound connections (NodeType::Input)
-- Enumerating all paths
paths = {}
for each node n in S do
visit(n,{})
function visit(node n, list l)
if n is not in l then
l.insert(n)
if n has no outbound connections then
paths.insert(l)
else
for each node m with an edge from n to m do
visit(m,l)
else
l.insert(n)
paths.insert(l)
l.remove_last_inserted()
-- any path in paths which has repeated nodes, has a cycle
@Lunderberg
Copy link

I think we can bail out early if we find a connection. It would also avoid having to have the std::set.

def would_cause_loop(i,j):                                                                  
    std::vector<bool> reachable(nodes.size(), False);                                       
    reachable[j] = True;                                                                    

    while True:                                                                             
        bool found_new_node = False                                                         

        for conn in connections:                                                            
            if (reachable[conn.origin] and                                                  
                   not reachable[conn.dest] and                                             
                   conn.type == ConnectionType::Normal):                                    
                if conn.dest == i:                                                          
                    return True                                                             
                else:                                                                       
                    reachable[conn.dest] = True                                             
                    found_new_node = True                                                   

        if not found_new_node:                                                              
            return False 

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment