笔试-羊狼过河

应用

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

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

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

实现

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
相关推荐
你才是向阳花1 天前
如何用Python实现飞机大战小游戏
开发语言·python·pygame
草莓熊Lotso1 天前
C++ 方向 Web 自动化测试实战:以博客系统为例,从用例到报告全流程解析
前端·网络·c++·人工智能·后端·python·功能测试
程序员爱钓鱼1 天前
Python编程实战——Python实用工具与库:Pandas数据处理
后端·python·ipython
程序员爱钓鱼1 天前
Python编程实战——Python实用工具与库:Numpy基础
后端·python·面试
程序员霸哥哥1 天前
从零搭建PyTorch计算机视觉模型
人工智能·pytorch·python·计算机视觉
晚秋大魔王1 天前
基于python的jlink单片机自动化批量烧录工具
前端·python·单片机
胖哥真不错1 天前
Python基于PyTorch实现多输入多输出进行CNN卷积神经网络回归预测项目实战
pytorch·python·毕业设计·课程设计·毕设·多输入多输出·cnn卷积神经网络回归预测
程序员-小李1 天前
基于PyTorch的动物识别模型训练与应用实战
人工智能·pytorch·python
闲人编程1 天前
Python在网络安全中的应用:编写一个简单的端口扫描器
网络·python·web安全·硬件·端口·codecapsule·扫描器
Mr_Xuhhh1 天前
GUI自动化测试--自动化测试的意义和应用场景
python·集成测试