简体   繁体   中英

Finding all paths in weighted graph from node A to B with weight of K or lower

I have a directed graph, with source and target. every edge is weighted on weight of 1. The nodes have no weight. I need to find an efficient way(I write on C#, but I don't think it is relevant), to find ALL the paths from the source to target, that the weight of the path(or the number of edges, which is the same with those details) be less or equal to a certain value, let's call it K.

A possible way I thought is to run Dijkstra on every value from 1 to K, but since K can be very big it won't be efficient. I have been looking on some answers, but also there was a very similar question to mine, I didn't find this answer as helpfully.

( Find all simple path from node A to node B in direct weighted graph with the sum of weighs less a certain value? )

You can simply run a DFS from the source to the target to analyze all paths. If you have to find number of paths you stop when you reach depth K returning 0 and when you reach the target returning 1 and if you need to describe the paths as well you can build a tree while exploring with the DFS. Complexity will be O(E) where E is the number of edges

Here a mixture of python and pseudo code:

def DFS(node, depth, target, visited, graph, max_depth):
  visited.add(node)
  if depth >= max_depth:
    return Null
  elif node == target:
    return new_tree_node(node)
  else:
    sub_trees = list()
    for connected_node in graph[node]:
      if connected_node not in visited:
        sub_tree = DFS(connected_node, depth+1, target, visited, graph, max_depth)
        if sub_tree != Null:
          sub_trees.append(sub_tree)

    if length(sub_trees) > 0:
      tree_node = new_tree_node(node)
      for sub_tree in sub_trees:
         tree_node.add_child(sub_tree)
      return tree_node
    else:
      return Null

tree = DFS(source, 0, target, set(), graph, K)

PS: this solution could easily be adapted to weighted graph as well

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM