传教士和野人过河问题



M个传教士,C个野人,M>=C,船上能载2人,要求过河时,传教士不能少于野人个数,否则被吃掉。怎么过河?
我看网上说这好像是一个经典问题,请问哪儿有详细的解法和源代码啊

编程题、传教士人数M,野人C,M≥C,开始都在岸左边,
①船只能载两人,传教士和野人都会划船,当然必须有人划船
②两岸边保证野人人数不能大于传教士人数   
把所有人都送过河,设计一方案,要求编程实现。 

思路:

深度搜索。

状态:左岸和右岸的人数+船的位置。

每一个状态下,会有5种状态可以转移,

即:

1,运送2个传教士到对岸;

2,运送2个野人到对岸;

3,运送1个传教士到对岸;

4,运送1个野人到对岸;

5,运送1个传教士和一个野人到对岸。

从初始状态开始搜,搜索这五种情况,

进入下一状态,判断该状态是否满足条件,

即两岸野人的个数是否比该岸的传教士多,

如果满足条件,则继续搜索该状态下的五种情况。

深度搜索下去,直到找到最后的解。

注意:

1,如果搜索的状态在之前已经出现过了,就不深入下去了,

否则会出现死循环,比如运两个野人过去,再运回来,状态复原了,

如果一直这么搜下去,就没玩没了了。

2,状态包括船的信息,如果两边的人数都是一样,但是船的位置不一样,

那么这是两种状态。

3,要搜索的目标状态是人都在对岸且船在对岸。

PS:

当M=C>3时,没有解。

当M>C时,有解。

#include <iostream> #include <vector> #include <string> #include <stdio.h> using namespace std; bool flag = true; //true:表示在右岸 vector<string> visit; //记录已经访问过的状态 bool dfs( int M, int C, int m, int c){ if( M<0||C<0||m<0||c<0) //非法 return false; if( (M&&C>M) ||(m&&c>m)) //野人会吃牧师 return false; if( flag&&M==0&&C==0 ||(!flag&&m==0&&c==0)) //全部运输过去 return true; //检查该节点是否出现过 char s[30]; if( !flag ) sprintf( s, "M=%d,C=%d,m=%d,c=%d,boat=left", M,C,m,c); else sprintf( s, "M=%d,C=%d,m=%d,c=%d,boat=right", m,c,M,C); string str(s); for( int i=0; i<visit.size(); i++) if( visit[i]==str) //该状态已经搜索过了 return false; visit.push_back(str); flag = !flag; if( dfs( m+2, c, M-2,C) ){ printf("2,0\n"); printf("%s\n",s); return true; } else if( dfs( m, c+2, M, C-2) ){ printf("0,2\n"); printf("%s\n",s); return true; } else if( dfs( m+1, c+1, M-1, C-1) ){ printf("1,1\n"); printf("%s\n",s); return true; } else if( dfs( m+1, c, M-1, C)){ printf("1,0\n"); printf("%s\n",s); return true; } else if( dfs( m, c+1, M, C-1)){ printf("0,1\n"); printf("%s\n",s); return true; } flag = !flag; visit.pop_back(); return false; } int main(){ char s[30]; int M=6,C=6,m=0,c=0; sprintf( s, "M=%d,C=%d,m=%d,c=%d,boat=left", M,C,m,c); printf("%s\n",s); if(!dfs(M,C,0,0)) cout << "Can not find the solution."<<endl; return 0; }

  • 0
    点赞
  • 3
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值