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 8 | Recursion<br />

8 2 Imagine a robot sitting on <strong>the</strong> upper left hand corner of an NxN grid The robot can<br />

only move in two directions: right and down How many possible paths are <strong>the</strong>re for<br />

<strong>the</strong> robot?<br />

FOLLOW UP<br />

Imagine certain squares are “off limits”, such that <strong>the</strong> robot can not step on <strong>the</strong>m<br />

Design an algorithm to get all possible paths for <strong>the</strong> robot<br />

SOLUTION<br />

Part 1: (For clarity, we will solve this part assuming an X by Y grid)<br />

Each path has (X-1)+(Y-1) steps Imagine <strong>the</strong> following paths:<br />

X X Y Y X (move right -> right -> down -> down -> right)<br />

X Y X Y X (move right -> down -> right -> down -> right)<br />

...<br />

CareerCup com<br />

pg 64<br />

Each path can be fully represented by <strong>the</strong> moves at which we move right That is, if I were to<br />

ask you which path you took, you could simply say “I moved right on step 3 and 4 ”<br />

Since you must always move right X-1 times, and you have X-1 + Y-1 total steps, you have<br />

to pick X-1 times to move right out of X-1+Y-1 choices Thus, <strong>the</strong>re are C(X-1, X-1+Y-1) paths<br />

(e g , X-1+Y-1 choose X-1):<br />

Part 2: Code<br />

(X-1 + Y-1)! / ((X-1)! * (Y-1)!)<br />

We can implement a simple recursive algorithm with backtracking:<br />

1 ArrayList current_path = new ArrayList();<br />

2 public static boolean getPaths(int x, int y) {<br />

3 Point p = new Point(x, y);<br />

4 current_path.add(p);<br />

5 if (0 == x && 0 == y) return true; // current_path<br />

6 boolean success = false;<br />

7 if (x >= 1 && is_free(x - 1, y)) { // Try right<br />

8 success = getPaths(x - 1, y); // Free! Go right<br />

9 }<br />

10 if (!success && y >= 1 && is_free(x, y - 1)) { // Try down<br />

11 success = getPaths(x, y - 1); // Free! Go down<br />

12 }<br />

13 if (!success) {<br />

14 current_path.remove(p); // Wrong way!<br />

15 }<br />

16 return success;<br />

17 }<br />

1 7 0

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

Saved successfully!

Ooh no, something went wrong!