All paths of length L from node n using python

前端 未结 5 1414
伪装坚强ぢ
伪装坚强ぢ 2020-12-16 07:34

Given a graph G, a node n and a length L, I\'d like to collect all (non-cyclic) paths of length L that depart from n.

Do you have any idea on how to approach this?

5条回答
  •  爱一瞬间的悲伤
    2020-12-16 08:31

    I would just like to expand on Lance Helsten's excellent answer:

    The depth-limited search searches for a particular node within a certain depth (what you're calling the length L), and stops when it finds it. If you will take a look at the pseudocode in the wiki link in his answer, you'll understand this:

    DLS(node, goal, depth) {
      if ( depth >= 0 ) {
        if ( node == goal )
          return node
    
        for each child in expand(node)
          DLS(child, goal, depth-1)
      }
    }
    

    In your case, however, as you're looking for all paths of length L from a node, you will not stop anywhere. So the pseudocode must be modified to:

    DLS(node, depth) {
        for each child in expand(node) {
          record paths as [node, child]
          DLS(child, depth-1)
        }
    }
    

    After you're done with recording all the single-link paths from successive nests of the DLS, just take a product of them to get the entire path. The number of these gives you the number of paths of the required depth starting from the node.

提交回复
热议问题