笔试-羊狼过河

应用

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

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

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

实现

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
相关推荐
racerun14 小时前
跳转链接批量解析工具 python
开发语言·python
q_354888515314 小时前
计算机毕业设计:Python当当网图书大数据分析平台 Django框架 爬虫 Pandas 可视化 大数据 大模型 书籍(建议收藏)✅
大数据·爬虫·python·机器学习·数据分析·django·课程设计
知智前沿14 小时前
什么是 RAG?通俗易懂讲解 + 核心流程梳理
人工智能·python
暮冬-  Gentle°15 小时前
Python内存管理机制:垃圾回收与引用计数
jvm·数据库·python
阿贵---15 小时前
使用PyQt5创建现代化的桌面应用程序
jvm·数据库·python
wertyuytrewm15 小时前
高级爬虫技巧:处理JavaScript渲染(Selenium)
jvm·数据库·python
不是株15 小时前
算 法
数据结构·python·算法
云姜.15 小时前
LLM接入方式
python
阳光永恒73615 小时前
Python零基础入门全套资料包免费分享 | 从0到1系统学习路线(含课件+源码+实战案例)
开发语言·python·学习·编程入门·python教程·编程学习·免费资料
紫丁香15 小时前
pytest_自动化测试1
开发语言·python·功能测试·单元测试·pytest