采蜜路径规划

华为笔试

第一题:采蜜路径规划

  • 平原上一群蜜蜂开始采蜜,要连续采集5片花丛后才可以归巢。已知5片花丛相对于蜂巢的坐标,请你帮助蜜蜂规划一下要访问的花丛的顺序,以使飞行的总距离最短。

  • 输入描述:以蜂巢为平面原点的5片花丛A、B、C、D、E的坐标,值为整数。

  • 输出:从出发到返回蜂巢的最短路径长度,取整数,即舍弃小数点后的值。

  • 例如:

    • 输入:200,0,200,10,200,50,200,30,200,25
    • 输出:456
  • 思路:首次找距离原点(蜂巢)最近的一点(比如A),计算O-A的距离;然后从其余点中找出距离A最近的点(比如B),然后计算A-B的距离…。不断重复,直至所有的点遍历完。

import math
input = [200, 0, 200 ,10 ,200 ,50 ,200, 30, 200 ,25]
def f(input):
    start = [0, 0] #蜂巢
    dis = 0 #飞行距离
    L = len(input)
    while L > 0:
        temp = []
        for i in range(L//2):
            d = math.sqrt(( input[i * 2]-start[0]) ** 2 + (input[2 * i + 1] - start[1]) ** 2 )
            temp.append(d)
        dis += min(temp)
#         print(min(temp))
        index = temp.index(min(temp))
        start = [input[index * 2], input[index * 2 + 1]]
        print(start)  #打印每次选出的花丛
        t1 = input.pop(index * 2)
        t2 = input.pop(index * 2)
        print(input, '\n')
        
        L = len(input)
        if L == 2:
            dis += math.sqrt( input[0] ** 2 + input[1] **2 )  #返回原点的距离
    return int(dis)
f(input)
[200, 0]
[200, 10, 200, 50, 200, 30, 200, 25] 

[200, 10]
[200, 50, 200, 30, 200, 25] 

[200, 25]
[200, 50, 200, 30] 

[200, 30]
[200, 50] 

[200, 50]
[] 






456
input2 = [1,1,2,0,3,3,-2,3,0,0.5]
f(input2)
[0, 0.5]
[1, 1, 2, 0, 3, 3, -2, 3] 

[1, 1]
[2, 0, 3, 3, -2, 3] 

[2, 0]
[3, 3, -2, 3] 

[3, 3]
[-2, 3] 

[-2, 3]
[] 






14
  • 其实本题就是一个路径规划问题,之前听说过算法【迪杰斯特拉】,但是只知道其核心的思想,代码自己写不出来。三个小时自己憋出来上面的代码,既有小开心,又有点失望。上述代码自己感觉是迪杰斯特拉,哈哈,不知不觉写出来了?

  • 说明:上述代码自己只是测试了两个简单的例子,其它例子不知道是否也能输出最短的路径,也欢迎大家对代码提出bug。

  • 另外,如果只是找到所有的点之间的最小距离,而不用返回原点,只需将代码最后的if语句去掉即可:

import math
input = [200, 0, 200 ,10 ,200 ,50 ,200, 30, 200 ,25]
def f(input):
    start = [0, 0] #蜂巢
    dis = 0 #飞行距离
    L = len(input)
    while L > 0:
        temp = []
        for i in range(L//2):
            d = math.sqrt(( input[i * 2]-start[0]) ** 2 + (input[2 * i + 1] - start[1]) ** 2 )
            temp.append(d)
        dis += min(temp)
#         print(min(temp))
        index = temp.index(min(temp))
        start = [input[index * 2], input[index * 2 + 1]]
        print(start)  #打印每次选出的花丛
        t1 = input.pop(index * 2)
        t2 = input.pop(index * 2)
        print(input, '\n')
        
        L = len(input)
    return int(dis)
f(input)
[200, 0]
[200, 10, 200, 50, 200, 30, 200, 25] 

[200, 10]
[200, 50, 200, 30, 200, 25] 

[200, 25]
[200, 50, 200, 30] 

[200, 30]
[200, 50] 

[200, 50]
[] 






250
  • 2
    点赞
  • 7
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值