# Finding Cheapest n-Path [closed]

Given a weighted directed acyclic graph, how can I find the cheapest path from an Origin Vertex to a Destination Vertex which goes through exactly n vertices?

Is there an efficient algorithm which accomplishes this? I know that I could use BFS to find all the possible paths between them, then filter that to get only the ones which are n long, and then sort them by cost. However, I would like to know if there's an algorithm which does not need to consider all possible paths to generate the result.

## closed as off-topic by Sasho Nikolov, D.W., Jan Johannsen, Aryeh, Peter Shor Jul 26 '18 at 20:06

This question appears to be off-topic. The users who voted to close gave this specific reason:

• "Your question does not appear to be a research-level question in theoretical computer science. For more information about the scope, please see help center. Your question might be suitable for Computer Science which has a broader scope." – Sasho Nikolov, D.W., Jan Johannsen, Aryeh
If this question can be reworded to fit the rules in the help center, please edit the question.

• What do you mean by efficient? – daniello Jul 25 '18 at 20:42
• I'll edit my question to clarify. I mean an algorithm which does not have to consider all possible paths, only n-paths, in order to generate the result. – Reubend Jul 25 '18 at 20:44
• The problem seems to be $\mathsf{NP}$-complete, since it reduces to Hamiltonian path in a DAG (just take $n=|V|$). May be this link can be useful: stackoverflow.com/questions/16124844/… – Lamine Jul 26 '18 at 12:52
• @PeterShor Forgive me if I'm being stupid here, but wouldn't it be impossible to visit the same node twice in a DAG? I think there would be a cycle if you could ever go back to somewhere you already visited, so it wouldn't be acyclical. – Reubend Jul 26 '18 at 20:46
• Of course it would. I didn't notice the DAG restriction. – Peter Shor Jul 26 '18 at 20:58

I am assuming you are given a weighted directed acyclic graph with source $s$ and destination $t$ and you want to find the shortest path from $s$ to $t$ with length exactly $n$ , this can be done easily with dynamic programming. Let $F(v,k)$ denote the shortest path from $v$ to $t$ with length exactly $k$ , we have
$F(t , k) = \begin{cases} 0 \ \ \ \ \text{ if }k = 0\\ +\infty \ \text{if } k > 0 \end{cases}$.
$F(v , k) = \begin{cases} \infty \text{ if }k = 0\\ \min_{u \in N^{+}(v)} F(u , k-1)+W(v,u) \end{cases}$
Solution is $F(s,n)$.
• Thanks! But is this method any more efficient than the one I posted in my original question? It seems like this will try every possible path from s to t in order to generate the answer. – Reubend Jul 26 '18 at 19:25