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 1 | Arrays and Strings<br />

1 6 Given an image represented by an NxN matrix, where each pixel in <strong>the</strong> image is 4<br />

bytes, write a method to rotate <strong>the</strong> image by 90 degrees Can you do this in place?<br />

SOLUTION<br />

1 0 1<br />

<strong>Cracking</strong> <strong>the</strong> <strong>Coding</strong> <strong>Interview</strong> | Data Structures<br />

pg 48<br />

The rotation can be performed in layers, where you perform a cyclic swap on <strong>the</strong> edges on<br />

each layer In <strong>the</strong> first for loop, we rotate <strong>the</strong> first layer (outermost edges) We rotate <strong>the</strong><br />

edges by doing a four-way swap first on <strong>the</strong> corners, <strong>the</strong>n on <strong>the</strong> element clockwise from <strong>the</strong><br />

edges, <strong>the</strong>n on <strong>the</strong> element three steps away<br />

Once <strong>the</strong> exterior elements are rotated, we <strong>the</strong>n rotate <strong>the</strong> interior region’s edges<br />

1 public static void rotate(int[][] matrix, int n) {<br />

2 for (int layer = 0; layer < n / 2; ++layer) {<br />

3 int first = layer;<br />

4 int last = n - 1 - layer;<br />

5 for(int i = first; i < last; ++i) {<br />

6 int offset = i - first;<br />

7 int top = matrix[first][i]; // save top<br />

8 // left -> top<br />

9 matrix[first][i] = matrix[last-offset][first];<br />

10<br />

11 // bottom -> left<br />

12 matrix[last-offset][first] = matrix[last][last - offset];<br />

13<br />

14 // right -> bottom<br />

15 matrix[last][last - offset] = matrix[i][last];<br />

16<br />

17 // top -> right<br />

18 matrix[i][last] = top; // right

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

Saved successfully!

Ooh no, something went wrong!