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 19 | Moderate<br />

24 Piece hasWon(Piece[][] board) {<br />

25 int N = board.length;<br />

26 Piece winner = Piece.Empty;<br />

27<br />

28 // Check rows <strong>and</strong> columns<br />

29 for (int i = 0; i < N; i++) {<br />

30 winner = getWinner(board, i, Check.Row);<br />

31 if (winner != Piece.Empty) {<br />

32 return winner;<br />

33 }<br />

34<br />

35 winner = getWinner(board, i, Check.Column);<br />

36 if (winner != Piece.Empty) {<br />

37 return winner;<br />

38 }<br />

39 }<br />

40<br />

41 winner = getWinner(board, -1, Check.Diagonal);<br />

42 if (winner != Piece.Empty) {<br />

43 return winner;<br />

44 }<br />

45<br />

46 // Check diagonal<br />

47 winner = getWinner(board, -1, Check.ReverseDiagonal);<br />

48 if (winner != Piece.Empty) {<br />

49 return winner;<br />

50 }<br />

51<br />

52 return Piece.Empty;<br />

53 }<br />

SUGGESTIONS AND OBSERVATIONS:<br />

»»<br />

Note that <strong>the</strong> runtime could be reduced to O(N) with <strong>the</strong> addition of row <strong>and</strong> column<br />

count arrays (<strong>and</strong> two sums for <strong>the</strong> diagonals)<br />

»»<br />

A common follow up (or tweak) to this question is to write this code for an NxN board.<br />

2 6 7<br />

<strong>Cracking</strong> <strong>the</strong> <strong>Coding</strong> <strong>Interview</strong> | Additional Review Problems

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

Saved successfully!

Ooh no, something went wrong!