c语言-商人过河游戏

#pragma once
#include <stdio.h>
#include <stdlib.h>

typedef struct {
	int a1, b1, a2, b2, times;
}drivers;

typedef struct {
	drivers r[100];
	int index;
	
}chain;
chain* p;
drivers  d[100],*l = d;

void put(int a1, int b1,int a2,int b2, int times) {
	p->index++;
	p->r[p->index].a1 = a1;
	p->r[p->index].b1 = b1;
	p->r[p->index].a2 = a2;
	p->r[p->index].b2 = b2;
	p->r[p->index].times = times;
}
int is_exist(int a1, int b1, int a2, int b2, int times) {
	for (int i = 0; i <= p->index; i++) {
		if (p->r[i].a1 == a1 &&
			p->r[i].b1 == b1 &&
			p->r[i].a2 == a2 &&
			p->r[i].b2 == b2 &&
			p->r[i].times%2 == times%2
		) {
			return 1;
		}
	}
	return 0;
}
void cache(int a1, int b1, int a2, int b2, int times) {
	d[times].a1 = a1;
	d[times].b1 = b1;
	d[times].a2 = a2;
	d[times].b2 = b2;
	d[times].times = times;
}

void print_cache(int max) {
	for (int i = 0; i <= max; i++) {
		if (d[i].times % 2 == 0) {
			printf("%d , %d  ->  %d , %d\n", d[i].a1, d[i].b1, d[i].a2, d[i].b2);
		}
		else {
			printf("%d , %d  <-  %d , %d\n", d[i].a2, d[i].b2, d[i].a1, d[i].b1);
		}
	}
	
}


//商人过河游戏

void run(int a1, int b1, int a2, int b2, int times) {
	cache(a1, b1, a2, b2, times);
	
	if (times % 2 == 1 && a1 == 3 && b1 == 3) {
		printf("---------------成功渡河---------------\n");
		print_cache(times);
		return;
	}
	if ((a1 && (a1 < b1)) || (a2 && (a2 < b2))) {
		//printf("此路不通\n");
		return;
	}
	
	if (is_exist(a1, b1, a2, b2, times)) {
		//printf("重复步骤\n");
		return;
	}
	else {
		put(a1, b1, a2, b2, times);
	}
	
	times++;
	for (int i = 0; i <=a1; i++) {
		for (int j = 0; j <=b1; j++) {
			if (i + j == 0 || i + j > 2) {
				continue;
			}
			run(a2+i,b2+j,a1-i,b1-j,times);
		}
	}
}

void river_main() {
	p = (chain*)malloc(sizeof(chain));
	l = (drivers*)calloc(sizeof(drivers),100);
	p->index = -1;
	run(3, 3, 0, 0, 0);
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值