#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);
}
c语言-商人过河游戏
于 2022-08-15 16:57:04 首次发布