Number of paths between two nodes in a DAG

后端 未结 2 539
遥遥无期
遥遥无期 2020-12-01 15:17

I want to find number of paths between two nodes in a DAG. O(V^2) and O(V+E) are acceptable.

O(V+E) reminds me to somehow use BFS or DFS but I don\'t know how. Can s

2条回答
  •  爱一瞬间的悲伤
    2020-12-01 15:31

    Do a topological sort of the DAG, then scan the vertices from the target backwards to the source. For each vertex v, keep a count of the number of paths from v to the target. When you get to the source, the value of that count is the answer. That is O(V+E).

提交回复
热议问题