gpt4 book ai didi

algorithm - 旅行票问题

转载 作者:塔克拉玛干 更新时间:2023-11-03 02:28:06 27 4
gpt4 key购买 nike

You are given a stack of travel tickets for various transportations that will take you from a point A to point B via several stops on the way. All of the tickets are out of order and you don't know where your journey starts, nor where it ends. Sort the tickets in the right order to complete your journey.

tickets = [  {from: "Barcelona", to: "New York"}  {from: "Barcelona", to: "Gerona"},  {from: "Madrid",    to: "Barcelona"},  {from: "Gerona",    to: "Barcelona"}]

我想,正确的顺序是:

tickets = [  {from: "Madrid",    to: "Barcelona"},  {from: "Barcelona", to: "Gerona"},  {from: "Gerona",    to: "Barcelona"},  {from: "Barcelona", to: "New York"}]

因为没有去马德里的机票,也没有从纽约来的机票。

该任务的最佳算法是什么?

语言是 JavaScript,但与语言无关的解决方案就足够了。

Update: I changed sample data to be not confused with One-way flight trip problem.

最佳答案

如果你可以多次访问一个节点(一个城市),这就是eulerian path problem .

Here有两种简单的算法来解决它,具体取决于您拥有的图形类型。您在第 3 页上有一个递归实现 here .

关于algorithm - 旅行票问题,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/3101402/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com