27.10.2014 Views

Cracking the Coding Interview, 4 Edition - 150 Programming Interview Questions and Solutions

Cracking the Coding Interview, 4 Edition - 150 Programming Interview Questions and Solutions

Cracking the Coding Interview, 4 Edition - 150 Programming Interview Questions and Solutions

SHOW MORE
SHOW LESS

Create successful ePaper yourself

Turn your PDF publications into a flip-book with our unique Google optimized e-Paper software.

<strong>Solutions</strong> to Chapter 8 | Recursion<br />

8.6 Implement <strong>the</strong> “paint fill” function that one might see on many image editing programs.<br />

That is, given a screen (represented by a 2-dimensional array of Colors), a<br />

point, <strong>and</strong> a new color, fill in <strong>the</strong> surrounding area until you hit a border of that color.<br />

SOLUTION<br />

pg 64<br />

First, let’s visualize how this method works. When we call Paint Fill (eg, “click” paint fill in <strong>the</strong><br />

image editing application) on, say, a green pixel, we want to “bleed” outwards. Pixel by pixel,<br />

we exp<strong>and</strong> outwards calling PaintFill on <strong>the</strong> surrounding pixel. When we hit a pixel that is<br />

not green, we stop. Surrounding green pixels may still be painted if <strong>the</strong>y are touched by<br />

ano<strong>the</strong>r Paint Fill operation.<br />

We can implement this algorithm recursively:<br />

1 enum Color {<br />

2 Black, White, Red, Yellow, Green<br />

3 }<br />

4 boolean PaintFill(Color[][] screen, int x, int y, Color ocolor,<br />

5 Color ncolor) {<br />

6 if (x < 0 || x >= screen[0].length ||<br />

7 y < 0 || y >= screen.length) {<br />

8 return false;<br />

9 }<br />

10 if (screen[y][x] == ocolor) {<br />

11 screen[y][x] = ncolor;<br />

12 PaintFill(screen, x - 1, y, ocolor, ncolor); // left<br />

13 PaintFill(screen, x + 1, y, ocolor, ncolor); // right<br />

14 PaintFill(screen, x, y - 1, ocolor, ncolor); // top<br />

15 PaintFill(screen, x, y + 1, ocolor, ncolor); // bottom<br />

16 }<br />

17 return true;<br />

18 }<br />

19<br />

20 boolean PaintFill(Color[][] screen, int x, int y, Color ncolor) {<br />

21 return PaintFill(screen, x, y, screen[y][x], ncolor);<br />

22 }<br />

1 7 5<br />

<strong>Cracking</strong> <strong>the</strong> <strong>Coding</strong> <strong>Interview</strong> | Concepts <strong>and</strong> Algorithms

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

Saved successfully!

Ooh no, something went wrong!