简体   繁体   English

无向图中给定两个顶点之间的最长简单路径

[英]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 中的节点st 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.另一个区别是,我们不会忽略已经访问过的节点,而是仅忽略已包含在当前路径中的节点。

  • Initialise a queue with a single path, containing just the node s .使用单个路径初始化一个队列,仅包含节点s
  • While the queue is non-empty:当队列非空时:
    • Poll a path from the queue.从队列中轮询path Let u be the last node in the path.u成为路径中的最后一个节点。
    • If u = t :如果u = t
      • If the number of nodes in path is at least k + 1 , then path is a solution;如果path的节点数至少为k + 1 ,则path是一个解; return with the result "true".返回结果“true”。
    • Otherwise if u != t :否则,如果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.对于u每个不在path邻居v ,通过将v附加到path来构造一个新path ,并将其插入队列中。
  • If the loop terminates without finding a solution, then none exists;如果循环在没有找到解的情况下终止,则不存在; return with the result "false".返回结果“false”。

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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM