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 8 Write an algorithm to print all ways of arranging eight queens on a chess board so<br />

that none of <strong>the</strong>m share <strong>the</strong> same row, column or diagonal<br />

SOLUTION<br />

1 7 7<br />

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

pg 64<br />

We will use a backtracking algorithm For each row, <strong>the</strong> column where we want to put <strong>the</strong><br />

queen is based on checking that it does not violate <strong>the</strong> required condition<br />

1 For this, we need to store <strong>the</strong> column of <strong>the</strong> queen in each row as soon as we have finalized<br />

it Let ColumnForRow[] be <strong>the</strong> array which stores <strong>the</strong> column number for each row<br />

2 The checks that are required for <strong>the</strong> three given conditions are:<br />

» On same Column : ColumnForRow[i] == ColumnForRow[j]<br />

» On same Diagonal: (ColumnForRow[i] - ColumnForRow[j] ) == ( i- j) or<br />

(ColumnForRow[j] - ColumnForRow[i]) == (i - j)<br />

1 int columnForRow[] = new int [8];<br />

2 boolean check(int row) {<br />

3 for (int i = 0; i < row; i++) {<br />

4 int diff = Math.abs(columnForRow[i] - columnForRow[row]);<br />

5 if (diff == 0 || diff == row - i) return false;<br />

6 }<br />

7 return true;<br />

8 }<br />

9<br />

10 void PlaceQueen(int row){<br />

11 if (row == 8) {<br />

12 printBoard();<br />

13 return;<br />

14 }<br />

15 for (int i = 0; i < 8; i++) {<br />

16 columnForRow[row]=i;<br />

17 if(check(row)){<br />

18 PlaceQueen(row+1);<br />

19 }<br />

20 }<br />

21 }

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

Saved successfully!

Ooh no, something went wrong!