笔试-羊狼过河

应用

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

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

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

实现

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
相关推荐
liuyunshengsir1 分钟前
PyTorch 动态量化(Dynamic Quantization)
人工智能·pytorch·python
电子云与长程纠缠10 分钟前
UE5制作六边形包裹球体效果
开发语言·python·ue5
DFT计算杂谈19 分钟前
KPROJ编译教程
java·前端·python·算法·conda
念恒123061 小时前
Python(循环中断)
开发语言·python
tsfy20031 小时前
Python 处理中文文件名的3个坑(附 Flask 上传解决函数)
开发语言·python·flask·文件上传·中文编码
AI技术控1 小时前
KV Cache 缓存机制的原理和应用:从 Transformer 推理到大模型服务优化
人工智能·python·深度学习·缓存·自然语言处理·transformer
vx-程序开发2 小时前
基于机器学习的动漫可视化系统的设计与实现-计算机毕业设计源码08339
java·c++·spring boot·python·spring·django·php
爱睡懒觉的焦糖玛奇朵2 小时前
【从视频到数据集:焦糖玛奇朵的魔法工具Video To YOLO Dataset】
人工智能·python·学习·yolo·音视频
石榴树下的七彩鱼2 小时前
医疗票据 OCR 识别 API 多场景落地指南:医保结算 + 商保理赔 + 医疗信息化(附 Python/Java 完整示例)
java·python·ocr·石榴智能·医疗票据ocr·医保结算·ocrapi
idingzhi3 小时前
A股量化策略日报(2026年05月22日)
android·开发语言·python·kotlin