如何找到最长的最小路径?

时间:2015-04-06 00:43:25

标签: python algorithm floyd-warshall

一只青蛙想过河。

河里有3块石头可以跳到。

她希望在所有可能的路径中选择导致最小最长跳跃的路径。

IE中。每个可能的路径将有一个最长的跳跃。她需要找到这个最长跳跃最小的路径。

2个海岸相距10个并且与y轴平行。

每个石头位置由x位置的列表x = [x1,x2,x3]和y位置的y = [y1,y2,y3]给出。

返回此路径中的最长跳转(四舍五入到最接近的整数)和路径本身通过路径中石头的列表x和y中的索引列表。

这是我的python代码,找到最长的跳转。

我如何跟踪路径本身?

我的代码看起来很笨,有3个嵌套循环是否有更好/更优雅的方式来编写这段代码?

def longestJump(x, y):
        best = 10
        for i in range(0,3):           
            for j in range(0,3):  
                for k in range(0,3):                
                   # first jump from shore to a stone
                   dist = x[i] 
                   # second jump between stones
                   dist = max(dist, round(math.sqrt((x[i]-x[j])**2 + (y[i]-y[j])**2))) 
                   # third jump between stones
                   dist = max(dist, round(math.sqrt((x[i]-x[k])**2 + (y[i]-y[k])**2))) 
                   dist = max(dist, round(math.sqrt((x[j]-x[k])**2 + (y[j]-y[k])**2)))
                   # last jump from a stone to the opposite shore 
                   dist = max(dist, 10 - x[j])
                   best = min(dist, best)
        return best

2 个答案:

答案 0 :(得分:0)

除了最终结果之外,你不需要取平方根。只需计算"距离平方"并与之比较。

不确定你在呼叫什么" round"无论是。这可能会造成一个错误。

此外,您不需要跳过所有" i == j"从内循环?

def longestJump(x, y):
        best = 10
        for i in range(0,3):           
            for j in range(0,3):  
                for k in range(0,3):                
                   # first jump from shore to a stone
                   dist = x[i] 
                   # second jump between stones
                   dist = max(dist, (x[i]-x[j])**2 + (y[i]-y[j])**2)
                   # third jump between stones
                   dist = max(dist, (x[i]-x[k])**2 + (y[i]-y[k])**2) 
                   dist = max(dist, x[j]-x[k])**2 + (y[j]-y[k])**2)
                   # last jump from a stone to the opposite shore 
                   dist = max(dist, 10 - x[j])
                   best = min(dist, best)
        return math.sqrt(best)

答案 1 :(得分:0)

您可以在itertools.permutations上使用range来简化三个循环。如果你传递长度为3的range,那将返回三元组。

至于跟踪路径,我认为如果你使用实际的if语句将每条路径的最大跳跃长度与迄今为止看到的最佳跳跃长度进行比较会更容易,而不是使用min。在if中,您还可以在保存跳转长度的同时保存其他信息(例如跳转幅度最小的路径)。

def longestJump(x, y):
    best_jump = 10 # infinity
    best_path = ()
    for i, j, k in itertools.permutations(range(3)):           
        jump0 = x[i]                                      # shore to i
        jump1 = sqrt((x[i]-x[j])**2 + (y[i]-y[j])**2)     # i to j
        jump2 = sqrt((x[j]-x[k])**2 + (y[i]-y[j])**2)     # j to k
        jump3 = 10 - x[k]                                 # k to far shore
        longest = max(jump0, jump1, jump2, jump3)
        if longest < best_jump:
            best_jump = longest
            best_path = (i, j, k)
    return best_jump, best_path

这总是希望使用所有三块宝石的路径。如果不需要,您可能想要迭代每个子集的排列。我不确定是否有一种特别简单的方法,但您可以尝试将itertools.combinations和上面的permutations代码结合起来。

相关问题