“人狼羊草”的计算机模拟暴力枚举

问题:人载狼羊草过河,一次摆渡除了人只能载一样,没人时,狼与羊、羊与草均不可独处。问如何过河。


#define STATE char #define PATH char STATE State[8] = { 1 }; PATH Path[16]; char* Bios[] = { "草", "羊", "狼", "人" }; void Ferry ( int state, int dir, int p ) { int i, bio, j; if ( !dir && ( state & 6 ) != 6 && ( state & 3 ) != 3 ) { Path[p] = 3; Ferry ( ~state & 7, 1, p + 1 ); } for ( i = 0; i < 3; i++ ) { if ( bio = state & ( 1 << i ) ) { state &= ~bio; if ( State[ dir ? ~state & 7 : state ] || ( state & 6 ) == 6 || ( state & 3 ) == 3 ) state |= bio; else if ( dir && !state ) { Path[p] = i; printf ( "摆渡过程,共往返 %d 次:/n", p + 1 ); for ( j = 0; j <= p; j++ ) printf ("%s:%s/n", (j & 1 ? "右往左" : "左往右"), Bios[Path[j]]); printf ( "/n" ); break; } else { State[ dir ? ~state & 7 : state ] = 1; Path[p] = i; Ferry ( ~state & 7, !dir, p + 1 ); State[ dir ? ~state & 7 : state ] = 0; state |= bio; } } } }


调用方式:

Ferry ( 7, 1, 0 );


参考:

《四人过桥——微软面试题的计算机模拟》

《生日悖论的泛化问题的讨论》

你可能感兴趣的:(数学和算法,《!——,代码集,——》,光宇广贞)