Reputation: 57
Input: n-node undirected graph G(V,E); nodes s and t in V; positive integer k
Question: Is there a simple path between s and t in G that contains at least k edges?
I know this problem is NP-hard but the thing is how and with which algorithm, should I approach to this question?
I have used BFS algorithm so far but I think its not the one that I should go with. At this point I don't know how to continue. I'm not very sure if I can find a solution for this question or not. An approximation would do too.
Upvotes: 2
Views: 1316
Reputation: 51093
This can be solved with a variation of BFS: instead of storing nodes in the queue, store paths. The other difference is that instead of ignoring nodes which are already visited, we only ignore nodes if they are already included in the current path.
s
.path
from the queue. Let u
be the last node in the path.u = t
:
path
is at least k + 1
, then path
is a solution; return with the result "true".u != t
:
v
of u
which is not already in path
, construct a new path by appending v
to path
, and insert it into the queue.The exact same solution works using DFS instead of BFS, by replacing the queue with a stack. In that case the stack will usually use less memory, but won't necessarily find the shortest solution. Since you just want to answer true/false if such a path exists, finding the shortest is unnecessary, so DFS is probably better.
Upvotes: 4