简体   繁体   English

在给定起始顶点和深度限制的情况下查找循环有向图中的所有可能路径

[英]Finding all possible paths in a cyclic directed graph given a starting vertex and a depth limitation

Consider the directed cyclic graph given below;考虑下面给出的有向循环图;

在此处输入图像描述

If a starting point (eg: vertex 0) and a maximum depth allowed is specified (eg: 5), what algorithm can be used to find all possible paths (note: a given vertex can be visited more than once)?如果指定了起点(例如:顶点 0)和允许的最大深度(例如:5),可以使用什么算法来查找所有可能的路径(注意:给定的顶点可以多次访问)?

What is the most efficient algorithm to implement this graph problem?实现这个图问题的最有效算法是什么?

Some of the possible paths for the above graph are given below in no particular order (starting with vertex 0 and maximum depth allowed is 5).上图的一些可能路径在下面没有特定顺序给出(从顶点 0 开始,允许的最大深度为 5)。

  • 0 -> 1 -> 2 -> 4 -> 1 -> 3 0 -> 1 -> 2 -> 4 -> 1 -> 3
  • 0 -> 1 -> 2 -> 4 -> 5 -> 1 0 -> 1 -> 2 -> 4 -> 5 -> 1
  • 0 -> 1 -> 2 -> 4 -> 5 -> 6 0 -> 1 -> 2 -> 4 -> 5 -> 6
  • 0 -> 1 -> 3 -> 5 -> 1 -> 3 0 -> 1 -> 3 -> 5 -> 1 -> 3

Pseudo algorithm for this will be an augmented BFS that keeps track of the path it has gone through.用于此的伪算法将是一个增强的 BFS,它跟踪它所经过的路径。 When it hits the required depth, it registers the path and then terminates.当它达到所需的深度时,它会注册路径然后终止。

Something like this (node.js style syntax):像这样的东西(node.js 风格的语法):

const requiredDepth = X
const relevantPaths = {}

const runBFS = (curNode, curPath = []) => {
    if (crPath.length === requiredDepth) {
        relevantPaths.push(curPath)
        return
    }

    for (let neighbor of curNode.neighbors) {
        const newPath = [ ...curPath, getEdge(curNode, neighbor) ]
        runBFS(neighbor, newPath)
    }
}

runBFS(root)

Hope this helps希望这可以帮助

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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