Collecting all paths of DAG with backward and forward links

可紊 提交于 2019-12-11 03:25:19

问题


I have a directed acyclic graph where each node is represent by a state

public class State{
   List<State> ForwardStates;
   List<State> backStates;
   string stateName;
}

where ForwardStates is a list of states via forward links from the current state. and backStates is a list of states via backward links from the current state.

I have two special state

State initialState (name=initial)
State finalState (name=final)

I wish to find all paths the start from initial state to final state, and populated in

List<List<string>> paths

For example given the graph like the following

Where backward links are represented by brown dotted arrow and forward links is represented by black concrete arrow, the possible paths are {{initial, b, a, final},{initial, c, final},{initial, b, initial,final}}

The rule is that from initial state, it must go through 1 or more backward links, before go through forward link, and once it switch to forward link, it will keep to forward links (i.e., it can't use the backward links anymore).

This question is an extension of this question(Collecting all paths of DAG).


回答1:


Do a DFS from initial state using the graph which using only backward links. From each of the nodes discovered by during this DFS (except initialState) do another DFS until you find the path to the target (using forward links only).

For each node u you discovered during DFS on backward links, the path is

path(initialState,u) ; path(u,finalState)

Where path(u,v) is the path found by the relevant DFS for this step.
Note that it might be invoked on a certain u more then once - you invoke it for each path you find from initialState to u, since it is a different required path.


If you only need number of paths it could be solved faster using topological sort and DP, but it is not the case in here.



来源:https://stackoverflow.com/questions/14652724/collecting-all-paths-of-dag-with-backward-and-forward-links

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