25.03.2013 Views

Cracking the Coding Interview - Fooo

Cracking the Coding Interview - Fooo

Cracking the Coding Interview - Fooo

SHOW MORE
SHOW LESS

You also want an ePaper? Increase the reach of your titles

YUMPU automatically turns print PDFs into web optimized ePapers that Google loves.

Solutions to Chapter 20 | Hard<br />

20 11 Imagine you have a square matrix, where each cell is filled with ei<strong>the</strong>r black or white<br />

Design an algorithm to find <strong>the</strong> maximum subsquare such that all four borders are<br />

filled with black pixels<br />

SOLUTION<br />

Assumption: Square is of size NxN<br />

This algorithm does <strong>the</strong> following:<br />

1 Iterate through every (full) column from left to right<br />

2 At each (full) column (call this currentColumn), look at <strong>the</strong> subcolumns (from biggest<br />

to smallest)<br />

2 9 3<br />

<strong>Cracking</strong> <strong>the</strong> <strong>Coding</strong> <strong>Interview</strong> | Additional Review Problems<br />

pg 92<br />

3 At each subcolumn, see if you can form a square with <strong>the</strong> subcolumn as <strong>the</strong> left side If<br />

so, update currentMaxSize and go to <strong>the</strong> next (full) column<br />

4 If N - currentColumn currentMaxSize) { // See step 4 above<br />

15 for (int row = 0; row < matrix.length; row++){<br />

16 // starting from <strong>the</strong> biggest<br />

17 int size = N - Math.max(row, col);<br />

18 while (size > currentMaxSize){<br />

19 if (isSquare(matrix, row, col, size)){<br />

20 currentMaxSize = size;<br />

21 sq = new Subsquare(row, col, size);<br />

22 break; // go to next (full) column

Hooray! Your file is uploaded and ready to be published.

Saved successfully!

Ooh no, something went wrong!