笔试-羊狼过河

应用

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

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

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

实现

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
相关推荐
孟健5 小时前
Karpathy 用 200 行纯 Python 从零实现 GPT:代码逐行解析
python
码路飞7 小时前
写了个 AI 聊天页面,被 5 种流式格式折腾了一整天 😭
javascript·python
曲幽9 小时前
FastAPI压力测试实战:Locust模拟真实用户并发及优化建议
python·fastapi·web·locust·asyncio·test·uvicorn·workers
敏编程14 小时前
一天一个Python库:jsonschema - JSON 数据验证利器
python
前端付豪14 小时前
LangChain记忆:通过Memory记住上次的对话细节
人工智能·python·langchain
databook14 小时前
ManimCE v0.20.1 发布:LaTeX 渲染修复与动画稳定性提升
python·动效
花酒锄作田1 天前
使用 pkgutil 实现动态插件系统
python
前端付豪1 天前
LangChain链 写一篇完美推文?用SequencialChain链接不同的组件
人工智能·python·langchain
曲幽1 天前
FastAPI实战:打造本地文生图接口,ollama+diffusers让AI绘画更听话
python·fastapi·web·cors·diffusers·lcm·ollama·dreamshaper8·txt2img
老赵全栈实战1 天前
Pydantic配置管理最佳实践(一)
python