Find all paths in directed cyclic graph as regular expression

|▌冷眼眸甩不掉的悲伤 提交于 2019-12-24 00:45:03

问题


Let G = (V,E,r) a rooted directed graph, defined by a set of vertices V and a set of edges E with a designated root node r. The graph may contain cycles. The task: Given two vertices x and y from V, find all paths from x to y.

Since cycles are allowed, the set of paths may obviously be infinite. Therefore, I want to find the set of paths in the form of a regular expression (Kleene Algebra). Here are a few examples: Examples graphs. Multiplication means sequence, so a path abc means first a, then b, then c. A set of paths a(b+c+d) means first a, then either b, c, or d. The kleene star a* means that a is repeated zero or more, a+ that a repeated one or more times.

Now I am looking for a way to construct these expressions algorithmically. What I have come up with so far:

  • Construct new expression tree T.
  • Start search at end node y.
  • Find all predecessors p to y.
  • for each p:
    • Add p as a child node to y in T.
    • Backtrack the path up the tree from p towards the root. If y is found along the way, then there is a cycle from y to p. Therefore, not only is p is a predecessor to y, but (path)* is also a predecessor to p. Therefore, add (path)* as a child node to p.
    • For all non-looping predecessors, recursive call with y := p as the new end node.

And finally:

  • Invert tree so it ends with the end node
  • Convert expression tree to expression (straightforward)

Not sure whether this will work, however, also worst case complexity will be somewhere above 2^n I guess. Does anyone know an algorithm for this or a similar problem?


回答1:


The general idea of your algorithm seems sound. However, I'm guessing that there may be many special cases in that back-tracking step that you'll have to code for. In particular, I don't see an easy way for that step to account for cycles within cycles, i.e. (path)* itself contains a term that needs a Kleene star.

I have separate suggestion though. The graph could be converted to an NFA, which would allow use of any of the well known algorithms to convert the NFA into a regular expression.

To convert the graph to an NFA:

  • Set node x as the start state.
  • Set node y as the only accept state.
  • For every node a, label all its incoming edges a.


来源:https://stackoverflow.com/questions/24682131/find-all-paths-in-directed-cyclic-graph-as-regular-expression

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!