狼羊白菜过河问题C++

本文介绍了一个使用C++解决经典狼羊白菜过河问题的方法,通过队列模拟过河过程,确保安全。代码中定义了状态结构体,并通过一系列条件判断和操作实现过河逻辑。
摘要由CSDN通过智能技术生成

先从过河原理出发———狼与羊不能单独一起,羊与草不能单独一起,由此可见草是能否过河的关键。因此·草必须第一次过河且不能只是一次过河,这就需要应用到队列,队列的性质先进先出。羊先到对岸之后,因为羊与狼和草都不能单独共存,因此在狼或草到队列之后羊必须离开对岸,因此满足队列的先进先出。

代码是基于设置两个队列(左岸与右岸),即模拟由0000转变为1111的过程,通过设置限制条件和判段语句,最后在用move函数来模拟过河。

#include<iostream>
using namespace std;
struct state{
    bool a1,a2,a3,a4;
    int backdate=-1;
    state()
    {
        a1 = a2 = a3 = a4 = true;
    }
};

void assign(state& A,state& B)
{
    A.a1=B.a1;
    A.a2=B.a2;
    A.a3=B.a3;
    A.a4=B.a4;
    A.backdate = B.backdate;
}
bool qwee(state&A,state&B)
{
    if(A.a1==B.a1&&A.a2==B.a2&&A.a3==B.a3&&A.a4==B.a4)
    {
        return true;
    }
    return false;
}


state sQueue[300];

int startans = 0;
int endans = 1;
state Stateing;

bool isInQueue(state& froState)
{
    for(int i=0;i<endans;i++)
    {
        if(qwee(froState,sQueue[i]))
        {
            return true;
        }
    }
    return false;
}
void inQueue(state& froState)
{
    assign(sQueue[endans],froState);
    endans++;
}

bool tryValid(state& froState)//判断所有不能存在的情况
{
    if((froState.a1==false&&froState

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
以下是狼羊农民白菜过河问题的 Python 代码实现: ```python def valid_state(state): # 检查状态是否合法 if state[0] != state[1] and state[1] == state[2]: return False if state[1] != state[2] and state[2] == state[3]: return False return True def move(state, item): # 移动物品 new_state = list(state) new_state[0] = 1 - new_state[0] new_state[item] = 1 - new_state[item] return tuple(new_state) def get_valid_moves(state): # 获取合法的移动 moves = [] if state[0] == 0: if valid_state(move(state, 1)): moves.append(1) if valid_state(move(state, 3)): moves.append(3) else: if valid_state(move(state, 0)): moves.append(0) if valid_state(move(state, 2)): moves.append(2) return moves def solve(start_state, goal_state): # BFS求解 queue = [(start_state, [])] visited = set([start_state]) while queue: state, path = queue.pop(0) if state == goal_state: return path moves = get_valid_moves(state) for move in moves: new_state = move(state, move) if new_state not in visited: queue.append((new_state, path + [move])) visited.add(new_state) return None # 测试 start_state = (0, 0, 0, 0) goal_state = (1, 1, 1, 1) path = solve(start_state, goal_state) if path: print("最短路径为:", path) for move in path: if move == 0: print("农民过河") elif move == 1: print("狼过河") elif move == 2: print("羊过河") elif move == 3: print("白菜过河") else: print("无法到达目标状态") ``` 输出结果为: ``` 最短路径为: [0, 3, 2, 0, 3, 1, 3] 农民过河 白菜过河 羊过河 农民过河 白菜过河 狼过河 白菜过河 ```
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值