// @Module: Main int main(void) { // Load puzzle-pieces: int i;Piece piece;int nPieces=sizeof(piecesStr)/11; printf("%d pieces\n",nPieces); for (i=0;i<nPieces;++i) { piece=strToInt64(piecesStr[i]); pushPiece(piece); #ifdef VERBOSE printPiece(piece); printf("---\n"); printPiece(flip(piece)); printf("---\n"); printPiece(rot(piece)); printf("---\n"); printPiece(flipRot(piece)); printf("---\n"); printf("~-~\n"); #endif } printf("STarTing::\n---!!\n"); if (!tryNextPiece(0)) { printf("No solution!\n"); return -1; } printf("Solved!"); return 0; }
// DFS, walk the game-tree: bool tryNextPiece(int depth) { char *word[]={"plain","flip","rot","rotFlip"}; Piece piece; int i,dir=0; #ifdef VERBOSE printf("Try depth(%d)\n",depth); #endif if (stackEmpty()) { // we've won! recurse-out answer printf("Winning!\n"); printf("BoardState:\n"); printPiece(board); printf("--~~~--\nunwinding solution:\n"); return true; } piece = popPiece(); i=tryDir(piece,5,depth); // Horizontal bits if (i>=0) goto weWin; //flip piece dir++; i=tryDir(flip(piece),5,depth); if (i>=0) goto weWin; // rot: dir++; i=tryDir(rot(piece),1,depth); if (i>=0) goto weWin; // rotFlip: dir++; i=tryDir(flipRot(piece),1,depth); if (i>=0) goto weWin; // not sure about this returning pieces bussiness... pushPiece(piece); // but each piece gotta be somewhere // so it makes somekindof sense... return false; weWin: printf("uw [%d]\n",depth); switch (dir){ case 0: printPiece(piece<<(5*i)); break; case 1: printPiece(flip(piece)<<(5*i)); break; case 2: printPiece(rot(piece)<<i); break; case 3: printPiece(flipRot(piece)<<i); break; } printf("Direction: %s, offset: %d\n",word[dir],i); return true; }
void displayPieces(const Piece *pieces, int length) { for (int i = 0; i < NUM_PIECES; i++) { printf("%d)\n", i + 1); printPiece(pieces[i]); printf("===============\n"); } }
// returns working index int tryDir(Piece piece,int shift,int depth) { int i; #ifdef VERBOSE printf("Working on:\n---..\n"); #endif for (i=0;i<4; ++i,piece <<=shift // try next row ) { #ifdef VERBOSE printPiece(piece); printf("--\n"); #endif if (5==shift) { if (takenH[i]) { continue; // place taken } } else { if (takenV[i]) { continue; } } if (pieceFits(piece)) { addPiece(piece); if (5==shift) takenH[i]=1; else takenV[i]=1; #ifdef VERBOSE printf("Fits!\n"); printf("board:\n"); printPiece(board); printf("~~~~\n"); #endif if (tryNextPiece(depth+1)) return i; // w/o removing rmPiece(piece); if (5==shift) takenH[i]=0; else takenV[i]=0; board &= ~piece; // rm piece } } return -1; }