商人过河问题(DFS)
来源:互联网 发布:Java仿hashmap实现 编辑:程序博客网 时间:2024/05/18 03:21
问题描述:
3个商人带着3个仆人过河,过河的工具只有一艘小船,只能同时载两个人过河,包括划船的人。在河的任何一边,只要仆人的数量超过商人的数量,仆人就会联合起来将商人杀死并抢夺其财物,问商人应如何设计过河顺序才能让所有人都安全地过到河的另一边。
详细过程参见《数学模型》第四版(姜启源)
3个商人带着3个仆人过河,过河的工具只有一艘小船,只能同时载两个人过河,包括划船的人。在河的任何一边,只要仆人的数量超过商人的数量,仆人就会联合起来将商人杀死并抢夺其财物,问商人应如何设计过河顺序才能让所有人都安全地过到河的另一边。
详细过程参见《数学模型》第四版(姜启源)
#include <cstdio>#define maxn 101int num;//number of bus or folint graph[maxn*maxn][maxn*maxn];int state[maxn][maxn];//when cross riverint c_bus[5] = {2, 1, 0, 1, 0};int c_fol[5] = {0, 1, 2, 0, 1};int b_step[maxn*maxn];int f_step[maxn*maxn];bool flag = false;void DFS(int bus, int fol, int step, int dir){ b_step[step] = bus, f_step[step] = fol; if(bus == 0 && fol == 0) { for(int i = 0; i <= step; i++) { printf("(%d,%d)", b_step[i], f_step[i]); if(i != step ) printf(" -> "); } printf("\n"); flag = true; } int fa = bus * ( num + 1 ) + fol; for(int i = 0; i < 5; i++) { if(dir){ int b_next = bus - c_bus[i], f_next = fol - c_fol[i]; if(b_next >= 0 && b_next < num+1 && f_next >= 0 && f_next < num + 1 && state[b_next][f_next]) { int son = b_next * ( num + 1 ) + f_next; if(!graph[fa][son] && !graph[son][fa]) { graph[fa][son] = 1; graph[son][fa] = 1; DFS(b_next, f_next, step + 1, !dir); graph[fa][son] = 0; graph[fa][son] = 0; } } } else{ int b_next = bus + c_bus[i], f_next = fol + c_fol[i]; if(b_next >= 0 && b_next < num + 1 && f_next >= 0 && f_next < num + 1 && state[b_next][f_next]) { int son = b_next * ( num + 1) + f_next; if(!graph[fa][son] && !graph[son][fa]) { graph[fa][son] = 1; graph[son][fa] = 1; DFS(b_next, f_next, step + 1, !dir); graph[fa][son] = 0; graph[fa][son] = 0; } } } }}int main(){ printf("Please input the number of the businessman: "); scanf("%d",&num); for(int i = 0; i < num + 1; i++) { state[i][0] = 1; state[i][num] = 1; state[i][i] = 1; } DFS(num, num, 0, 1); if(!flag) printf("they can't cross the river.");}
0 0
- 商人过河问题(DFS)
- 商人过河问题
- 商人过河问题
- 商人过河问题
- 过河问题(牛虎过河、商人仆人过河、农夫妖怪过河、传教士野人过河)(第2届第2题)
- 商人过河问题C语言源码.c
- 商人过河问题的Java实现1
- 商人过河问题的Java实现2
- 三商人三仆人过河问题
- 作为非计算机专业小白,第一次写作(c++解决商人过河问题)
- 修正我上次关于《商人过河的问题》
- 商人过河 决策
- 商人过河的另一个版本(商人数, 船载人数可变)
- 商人过河数学模型求源程序
- 商人过河 Matlab程序实现
- 【数学模型】商人们怎样过河?
- [数学模型]商人怎样安全过河
- 我用c语言写了一个关于商人过河的问题
- 第四周 项目三 用对象数组操作长方柱类
- groovy 速学 - 30 - Sql
- 内核层读写应用层文件,使用filp_open函数。
- AOJ 593分组玩游戏:利用STL 快速排序
- [算法] Alpha-Beta搜索
- 商人过河问题(DFS)
- Linux常用命令大全
- android基础学习之sqlite
- js判断字符串开头和分割
- 腾讯笔试 求基因碱基的逆序数
- Linux下Tomcat的启动、关闭、杀死进程
- 循环-13. 求特殊方程的正整数解(15)
- 枚举百鸡问题的算法优化
- Maven常用命令