Finding all cycles in a directed graph

前端 未结 17 2467
渐次进展
渐次进展 2020-11-22 05:47

How can I find (iterate over) ALL the cycles in a directed graph from/to a given node?

For example, I want something like this:

A->B->A
A->B         


        
17条回答
  •  渐次进展
    2020-11-22 06:05

    Depth first search with backtracking should work here. Keep an array of boolean values to keep track of whether you visited a node before. If you run out of new nodes to go to (without hitting a node you have already been), then just backtrack and try a different branch.

    The DFS is easy to implement if you have an adjacency list to represent the graph. For example adj[A] = {B,C} indicates that B and C are the children of A.

    For example, pseudo-code below. "start" is the node you start from.

    dfs(adj,node,visited):  
      if (visited[node]):  
        if (node == start):  
          "found a path"  
        return;  
      visited[node]=YES;  
      for child in adj[node]:  
        dfs(adj,child,visited)
      visited[node]=NO;
    

    Call the above function with the start node:

    visited = {}
    dfs(adj,start,visited)
    

提交回复
热议问题