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

You also want an ePaper? Increase the reach of your titles

YUMPU automatically turns print PDFs into web optimized ePapers that Google loves.

<strong>Solutions</strong> to Chapter 4 | Trees <strong>and</strong> 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 />

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 <strong>and</strong>, 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 <strong>and</strong> 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 />

CareerCup.com<br />

1 2 4

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

Saved successfully!

Ooh no, something went wrong!