Yagimutsu
Yagimutsu

Reputation: 57

Longest simple path between given two vertices in an undirected graph

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

Answers (1)

kaya3
kaya3

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.

  • Initialise a queue with a single path, containing just the node s.
  • While the queue is non-empty:
    • Poll a path from the queue. Let u be the last node in the path.
    • If u = t:
      • If the number of nodes in path is at least k + 1, then path is a solution; return with the result "true".
    • Otherwise if u != t:
      • For each neighbour v of u which is not already in path, construct a new path by appending v to path, and insert it into the queue.
  • If the loop terminates without finding a solution, then none exists; return with the result "false".

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

Related Questions