// This is the core solution bool Board::RecursiveSetBlock(Blocks &bs, size_t block_index) { Block* block = bs[block_index]; size_t xmax = width - block->width; size_t ymax = height - block->height; for (size_t x = 0; x <= xmax; x++) { for (size_t y = 0; y <= ymax; y++) { // if there is a place for block, process. if (SetBlock(block, x, y)) { // If the block is the last one, solution found. if (block_index == bs.size() - 1) { cout << "Step: Put block " << block_index << " at [" << x << ", " << y << "]" << endl; block->Print(width, height, x, y, "Block " + to_string(block_index)); return true; } // If not the last one, process other blocks. if (RecursiveSetBlock(bs, block_index + 1)) { // If all other blocks are positioned correctly, solution found. cout << "Step: Put block " << block_index << " at [" << x << ", " << y << "]" << endl; block->Print(width, height, x, y, "Block " + to_string(block_index)); return true; } else { // If not able to found a solution for other blocks, rollback current block, // and continually find next available position for current block. ClearBlock(block, x, y); continue; } } } } return false; }