笔试-羊狼过河

应用

羊、狼、农夫都在岸边,当羊的数量小于狼的数量时,狼会攻击羊,农夫有损失。

现有一艘容量固定的船(农夫不占船的容量),能够承载固定数量的动物。

在不损失羊情况下,将全部羊和狼运到对岸的最小次数,只计算农夫去对岸的次数,回程时农夫不会运送羊和狼。

实现

python 复制代码
strs = input("请输入羊的数量、狼的数量、船的容量:").split()
lst = [int(i) for i in strs]
M = lst[0]
N = lst[1]
X = lst[2]

result = []

def transport(count, left_m, left_n, right_m, right_n):
    if left_m == 0 and left_n == 0 and right_m == M and right_n == N:
        result.append(count)
    else:
        for i in range(0, left_m+1):
            for j in range(0, left_n+1):

                if i != 0 and j !=0:
                    if i+j <= X:
                        
                        temp_left_m = left_m - i
                        temp_left_n = left_n - j
                        temp_right_m = right_m + i
                        temp_right_n = right_n + j

                        if temp_left_m >= temp_left_n  or temp_left_m == 0:
                            if temp_right_m >= temp_right_n or temp_right_m == 0:

                                temp_count = count + 1
                                transport(temp_count, temp_left_m, temp_left_n, temp_right_m, temp_right_n)
# 运行
transport(0, M, N, 0, 0)
if result:
    result.sort()
    print(result[0])
else:
    print(0)
powershell 复制代码
请输入羊的数量、狼的数量、船的容量:5 3 3
3

请输入羊的数量、狼的数量、船的容量:5 4 1
0
相关推荐
云烟成雨TD几秒前
LangFlow 1.x 系列【7】工作流创建与部署指南
人工智能·python·agent
月疯15 分钟前
np.where()[0]的用法
开发语言·python·numpy
KaMeidebaby25 分钟前
卡梅德生物技术快报|纳米抗体技术全套实操流程:AFB1 全合成文库淘选 + 分子对接定点突变参数手册
人工智能·python·tcp/ip·算法·机器学习
hnxaoli33 分钟前
统信小程序(十六)xls转xlsx
开发语言·python·小程序
梦想三三41 分钟前
Flask + PyTorch模型部署实战:从训练权重到API接口完整工程解析(附完整代码)
人工智能·pytorch·python·flask·模型推理·ai 工程化
用户298698530141 小时前
Python 实现 Excel 与 TXT 文本的高效转换与导出
后端·python·excel
杨超越luckly1 小时前
Agent 应用指南:基于 OurAirports 的中国机场设施数据可视化
python·html·github·可视化·机场设施
卷无止境1 小时前
pytest 从零到实战:要想代码好,测试少不了
后端·python
吃糖的小孩1 小时前
# RootGraph v1.5 收工:我给 QQ 机器人补上了聊天运行时的“黑匣子”
python
hangyuekejiGEO2 小时前
临沂GEO技术服务方案对比分析
大数据·人工智能·python