笔试-羊狼过河

应用

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

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

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

实现

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
相关推荐
benchmark_cc5 小时前
REST API 和 Python SDK 应该怎么选?量化交易数据接口选型实战
开发语言·python·数据分析·pandas·量化交易·股票数据·quantdash
2601_962382436 小时前
python快乐编程网络爬虫课后答案
python·网络爬虫·学习工具·课后答案·刷题app
鹏哥带你干乡墅6 小时前
优选乡墅赋能培训平台如何帮助提升乡村建设?
大数据·人工智能·python
veminhe7 小时前
python调用接口获取网络信息
python
Allen_LVyingbo8 小时前
医疗AI基础2026-构建可靠智能体的编程路径(上)
大数据·数据库·人工智能·python·自动化
Rnan-prince8 小时前
堆与TopK · 从零到通透 —— 9 节全系列复盘
python·算法
2601_962294619 小时前
Python接口自动化测试实战:使用requests库
python·接口自动化测试·异常处理·requests库·api测试
砚底藏山河10 小时前
【量化纯GET实战 #23】多股票相关性:用收益率看板块联动
java·数据库·python·金融·数据分析
阿童木写作10 小时前
跨境电商翻译工具推荐:批量图片翻译+视频字幕实时翻译
人工智能·python·音视频
晶捷软件10 小时前
晶捷智能:集团型制造企业ERP如何实现多工厂统一管控
大数据·人工智能·python·制造