问题
Given a graph G(V, E), a source vertex s and destination vertex d, the problem is to find all possible paths from s to d where G may contain loops and cycles. I want to get all simple paths, no cycle is allowed.
What would be the complexity of this problem?
回答1:
This problem is NP-hard, since its output may have an exponential size w.r.t its input.
Finding the longest path between two points is already NP-hard (reduction to hamiltonian path problem), so finding all of them is as well.
You can also see that this problem has an exponential complexity by seeing that there might be an exponential number of paths between two vertices in a graph.
Here is a small example:
Let G
be a graph with 3n+2
vertices. Let V = {s,d} U {a1, ..., an} U {b1, ..., bn} U {c1, ..., cn}
be its vertex set.
We build edges as follow:
-from s
to a1
- for i in 1...n
, we build an edge from ai to bi
, from ai to ci
- for i in 1..n-1
, we build an edge from bi to ai+1
, from ci to ai+1
.
- from bn to d
, from cn to d
.
As you can see, there are about 2^n
paths from s
to d
.
来源:https://stackoverflow.com/questions/58934990/all-possible-path-in-a-graph