25.03.2013 Views

Cracking the Coding Interview - Fooo

Cracking the Coding Interview - Fooo

Cracking the Coding Interview - Fooo

SHOW MORE
SHOW LESS

Create successful ePaper yourself

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

Solutions to Chapter 3 | Stacks and Queues<br />

3 4 In <strong>the</strong> classic problem of <strong>the</strong> Towers of Hanoi, you have 3 rods and N disks of different<br />

sizes which can slide onto any tower The puzzle starts with disks sorted in ascending<br />

order of size from top to bottom (e g , each disk sits on top of an even larger one) You<br />

have <strong>the</strong> following constraints:<br />

SOLUTION<br />

(A) Only one disk can be moved at a time<br />

(B) A disk is slid off <strong>the</strong> top of one rod onto <strong>the</strong> next rod<br />

(C) A disk can only be placed on top of a larger disk<br />

Write a program to move <strong>the</strong> disks from <strong>the</strong> first rod to <strong>the</strong> last using Stacks<br />

CareerCup com<br />

pg 52<br />

We need to move N disks from Rod 1 to Rod 3, but let’s start from <strong>the</strong> beginning Moving <strong>the</strong><br />

top disk is easy - we just move it to Disk 3<br />

Can we move <strong>the</strong> top two disks? Yes:<br />

1 Move Disk 1 from Rod 1 to Rod 2<br />

2 Move Disk 2 from Rod 1 to Rod 3<br />

3 Move Disk 1 from Rod 2 to Rod 3<br />

Can we move <strong>the</strong> top three disks?<br />

1 We know we can move <strong>the</strong> top two disks around from one Rod to ano<strong>the</strong>r (as shown<br />

earlier), so let’s assume we have moved Disk 1 and 2 to Rod 2<br />

2 Move Disk 3 to Rod 3<br />

3 Again we know we can move <strong>the</strong> top two disks around, so let’s move <strong>the</strong>m from Rod 2<br />

to Rod 3<br />

This approach leads to a natural recursive algorithm:<br />

1 public static void main(String[] args)<br />

2 int n = 5;<br />

3 Tower[] towers = new Tower[n];<br />

4 for (int i = 0; i < 3; i++) towers[i] = new Tower(i);<br />

5 for (int i = n - 1; i >= 0; i--) towers[0].add(i);<br />

6 towers[0].moveDisks(n, towers[2], towers[1]);<br />

7 }<br />

8<br />

9 public class Tower {<br />

10 private Stack disks;<br />

11 private int index;<br />

12 public Tower(int i) {<br />

1 1 8

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

Saved successfully!

Ooh no, something went wrong!