36S-CS106X-Practice-Key

36S-CS106X-Practice-Key - CS106X Handout 36S Autumn 2010...

Info iconThis preview shows pages 1–3. Sign up to view the full content.

View Full Document Right Arrow Icon

Info iconThis preview has intentionally blurred sections. Sign up to view the full version.

View Full DocumentRight Arrow Icon
This is the end of the preview. Sign up to access the rest of the document.

Unformatted text preview: CS106X Handout 36S Autumn 2010 December 7 th , 2010 CS106X Practice Final Solution Solution 1: Recursive Backtracking and the 70 2 Puzzle bool Solve(Grid<bool>& board) { // assume board is initially cleared return Solve(board, 1); } bool Solve(Grid<int>& board, int dimension) { if (dimension == 25) return true; for (int row = 0; row < board.numRows() - dimension; row++) { for (int col = 0; col < board.numCols() - dimension; col++) { if (CanPlaceSquare(board, row, col, dimension)) { PlaceSquare(board, dimension, row, col); if (Solve(board, dimension + 1)) return true; LiftSquare(board, dimension, row, col); } } } return false; } Solution 2: Quadtrees quadtree *gridToQuadtree(Grid<bool>& image) { return gridToQuadtree(image, 0, image.numCols(), 0, image.numRows()); } quadtree *gridToQuadtree(Grid<bool>& image, int lowx, int highx, int lowy, int highy) { quadtree *qt = new quadtree; qt->lowx = lowx; qt->highx = highx - 1; qt->lowy = lowy; qt->highy = highy - 1; if (allPixelsAreTheSameColor(image, lowx, highx, lowy, highy)) { qt->isBlack = image[lowx][lowy]; for (int i = 0; i < 4; i++) qt->children[i] = NULL; } else { int midx = (highx - lowx) / 2; int midy = (highy - lowy) / 2; qt->children[NW] = gridToQuadTree(image, lowx, midx, midy, highy); qt->children[NE] = gridToQuadtree(image, midx, highx, midy, highy); qt->children[SE] = gridToQuadTree(image, midx, highx, lowy, midy); qt->children[SW] = gridToQuadTree(image, lowx, midx, lowy, midy); } // assume NW, NE, etc are constants/#defines return qt; } Solution 3: Encoding General Trees struct genTreeNode { int value; Vector<genTreeNode *> children; }; struct binTreeNode { int value; binTreeNode *left; binTreeNode *right; }; binTreeNode *encode(Vector<genTreeNode *>& siblings, int start) { if (start == siblings.size()) return NULL; binTreeNode *root = new binTreeNode; root->value = siblings[start]->value; root->left = encode(siblings[start]->children, 0); root->right = encode(siblings, start + 1); return root; } binTreeNode *encode(genTreeNode *root) {...
View Full Document

Page1 / 5

36S-CS106X-Practice-Key - CS106X Handout 36S Autumn 2010...

This preview shows document pages 1 - 3. Sign up to view the full document.

View Full Document Right Arrow Icon
Ask a homework question - tutors are online