[英]Longest simple path between given two vertices in an undirected graph
Input: n-node undirected graph G(V,E) ;输入: n 节点无向图G(V,E) ; nodes s and t in V; V 中的节点s和t ; positive integer k正整数k
Question: Is there a simple path between s and t in G that contains at least k edges?问题: G 中的 s 和 t 之间是否有一条至少包含 k 条边的简单路径?
I know this problem is NP-hard but the thing is how and with which algorithm, should I approach to this question?我知道这个问题是 NP-hard 问题,但问题是如何以及使用哪种算法,我应该解决这个问题吗?
I have used BFS algorithm so far but I think its not the one that I should go with.到目前为止,我已经使用了 BFS 算法,但我认为它不是我应该使用的算法。 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.近似值也可以。
This can be solved with a variation of BFS: instead of storing nodes in the queue, store paths.这可以通过 BFS 的变体来解决:不是在队列中存储节点,而是存储路径。 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
.使用单个路径初始化一个队列,仅包含节点s
。path
from the queue.从队列中轮询path
。 Let u
be the last node in the path.让u
成为路径中的最后一个节点。u = t
:如果u = t
:
path
is at least k + 1
, then path
is a solution;如果path
的节点数至少为k + 1
,则path
是一个解; return with the result "true".返回结果“true”。u != t
:否则,如果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.对于u
每个不在path
邻居v
,通过将v
附加到path
来构造一个新path
,并将其插入队列中。The exact same solution works using DFS instead of BFS, by replacing the queue with a stack.完全相同的解决方案使用 DFS 而不是 BFS,通过用堆栈替换队列。 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.由于您只想在这样的路径存在时回答真/假,因此不需要找到最短的,因此 DFS 可能更好。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.