笔试-羊狼过河

应用

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

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

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

实现

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
相关推荐
jufeng13079 小时前
【系列:手搓自主 AI Agent:Hermes 架构原理剖析 · 第 11 篇】
python·ai agent·mcp
En^_^Joy9 小时前
Django项目配置全攻略:settings配置文件
后端·python·django
for_ever_love__10 小时前
python基础语法学习: 异常的传递性
开发语言·python·学习
AC赳赳老秦10 小时前
公开图片 OCR 数据提取:OpenClaw 合规采集公开信息图,识别文字与表格并转化为结构化数据
java·大数据·前端·数据库·python·php·openclaw
麻雀飞吧11 小时前
零基础选量化工具,先把问题说清楚
人工智能·python
段一凡-华北理工大学11 小时前
AI推动工业智能化转型~系列文章20:工业 AI 平台架构:云-边-端协同的技术体系
人工智能·python·架构·工业平台·云-边协同
CodeBlog-star11 小时前
Harness Engineering:Pi Agent 架构深度解析
人工智能·python·架构·harness工程
简不变12 小时前
将components下的文件夹复制到别一个文件夹下,并重新生成CMakelist.txt文件
python
AC赳赳老秦12 小时前
风控岗应用:OpenClaw 采集公开司法与经营异常数据,自动生成企业风险评估报告
大数据·c语言·数据库·人工智能·python·php·openclaw