[英]Find the shortest path in a graph visiting all nodes
I have a weighted and undirected graph G
with n
vertices. 我有一个加权和无向图G
有n
个顶点。 Two of these vertices are X
and Y
. 这些顶点中的两个是X
和Y
I need to find the shortest path that starts at X
, ends at Y
and passes through all the vertices of G (in any order). 我需要找到从X
开始的最短路径,在Y
处结束并穿过G的所有顶点(以任何顺序)。
How I can do this? 我怎么能这样做?
This is not the Travelling Salesman Problemm: I don't need to visit each vertex just once and I don't want to return to the first vertex. 这不是旅行商问题:我不需要访问每个顶点一次,我不想返回到第一个顶点。
This problem is basically NP-Hard, I am going to give a sketch of a proof (and not a proper reduction), that explains that unless P = NP , there is no polynomial solution to this problem. 这个问题基本上是NP-Hard,我将给出一个证明的草图(而不是一个适当的减少),这解释了除非P = NP ,否则没有多项式解决这个问题。
Assume torwards contradiction that this problem can be solved in polynomial time O(P(n))
by some algorithm A(G,x,y)
假设通过某种算法A(G,x,y)
在多项式时间O(P(n))
解决该问题的矛盾矛盾
Define the following algorithm: 定义以下算法:
HamiltonianPath(G):
for each pair (x,y):
if A(G(x,y) == |V| - 1):
return true
return false
This algorithm solves Hamiltonian Path Problem . 该算法解决了哈密顿路径问题 。
-> If there is a path between some pair
x,y
that goes through all nodes and its length is exactly|V|
- >如果某个对x,y
之间有一条路径通过所有节点,其长度正好是|V|
, it means it did not use any vertex twice, and the path found is Hamiltonian. ,这意味着它没有使用任何顶点两次,并且找到的路径是哈密顿量。<- If there is a Hamiltonian Path v1->v2->...->vn, then when invoking
A(G,v1,vn)
, you will find the shortest possible path, which its length is at most|V|-1
(and it cannot be less because it needs to go through all vertices), and the algorithm will yield true. < - 如果存在哈密顿路径v1-> v2 - > ...-> vn,则在调用A(G,v1,vn)
,您将找到最短路径,其长度最多为|V|-1
(并且它不能少,因为它需要遍历所有顶点),算法将产生true。
Complexity: 复杂:
Complexity of the algorithm is O(n^2 * P(n))
, which is polynomial time. 算法的复杂度为O(n^2 * P(n))
,即多项式时间。
So, assuming such an algorithm exists, Hamiltonian Path can be solved in polynomial time, and since it (Hamiltonian Path Problem) is NP-Complete , P=NP. 因此,假设存在这样的算法,哈密顿路径可以在多项式时间内求解,并且因为它(哈密顿路径问题)是NP完全的 ,P = NP。
Try to look at Dijkstra's algorithm 试着看看Dijkstra的算法
The basic idea is to filter the routes that traverse all the nodes and get the route with the shortest path. 基本思想是过滤遍历所有节点的路由并获得具有最短路径的路由。
Bu actually this may be not an optimal way. 事实上,这可能不是一种最佳方式。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.