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 4 | Trees and Graphs<br />

4 2 Given a directed graph, design an algorithm to find out whe<strong>the</strong>r <strong>the</strong>re is a route between<br />

two nodes<br />

SOLUTION<br />

CareerCup com<br />

pg 54<br />

This problem can be solved by just simple graph traversal, such as depth first search or<br />

breadth first search We start with one of <strong>the</strong> two nodes and, during traversal, check if <strong>the</strong><br />

o<strong>the</strong>r node is found We should mark any node found in <strong>the</strong> course of <strong>the</strong> algorithm as ‘already<br />

visited’ to avoid cycles and repetition of <strong>the</strong> nodes<br />

1 public enum State {<br />

2 Unvisited, Visited, Visiting;<br />

3 }<br />

4<br />

5 public static boolean search(Graph g, Node start, Node end) {<br />

6 LinkedList q = new LinkedList(); // operates as Stack<br />

7 for (Node u : g.getNodes()) {<br />

8 u.state = State.Unvisited;<br />

9 }<br />

10 start.state = State.Visiting;<br />

11 q.add(start);<br />

12 Node u;<br />

13 while(!q.isEmpty()) {<br />

14 u = q.removeFirst(); // i.e., pop()<br />

15 if (u != null) {<br />

16 for (Node v : u.getAdjacent()) {<br />

17 if (v.state == State.Unvisited) {<br />

18 if (v == end) {<br />

19 return true;<br />

20 } else {<br />

21 v.state = State.Visiting;<br />

22 q.add(v);<br />

23 }<br />

24 }<br />

25 }<br />

26 u.state = State.Visited;<br />

27 }<br />

28 }<br />

29 return false;<br />

30 }<br />

1 2 4

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

Saved successfully!

Ooh no, something went wrong!