Algorithmic This page intentionally left blank ALGORITHMIC PUZZLES

Anany Levitin and Maria Levitin

3 3 Oxford University Press, Inc., publishes works that further Oxford University’s objective of excellence in research, scholarship, and education.

Oxford New York Auckland Cape Town Dar es Salaam Hong Kong Karachi Kuala Lumpur Madrid Melbourne Mexico City Nairobi New Delhi Shanghai Taipei Toronto

With offices in Argentina Austria Brazil Chile Czech Republic France Guatemala Hungary Italy Japan Poland Portugal Singapore South Korea Switzerland Thailand Ukraine Vietnam

Copyright © 2011 by Oxford University Press

Published by Oxford University Press, Inc. 198 Madison Avenue, New York, New York 10016 www.oup.com

Oxford is a registered trademark of Oxford University Press

All rights reserved. No part of this publication may be reproduced, stored in a retrieval system, or transmitted, in any form or by any means, electronic, mechanical, photocopying, recording, or otherwise, without the prior permission of Oxford University Press.

Library of Congress Cataloging-in-Publication Data

Levitin, Anany. Algorithmic puzzles / Anany Levitin, Maria Levitin. p. cm. Includes bibliographical references and index. ISBN 978-0-19-974044-4 (pbk.) 1. Mathematical recreations. 2. Algorithms. I. Levitin, Maria. II. Title. QA95.L475 2011 793.74—dc22 2010052043

987654321

Printed in the United States of America on acid-free paper To Max with love This page intentionally left blank Contents

Preface ix Acknowledgments xiii List of Puzzles xv Tutorial Puzzles xv Main Section Puzzles xvi The Epigraph : Who said what? xxi

1. Tutorials 3 General Strategies for Algorithm Design 3 Analysis Techniques 22

2. Puzzles 32 Easier Puzzles (#1 to #50) 32 Puzzles of Medium Difficulty (#51 to #110) 45 Harder Puzzles (#111 to #150) 60

3. Hints 72

4. Solutions 82

References 241 Design Strategy and Analysis Index 247 Index of Terms and Names 254 This page intentionally left blank PrefaceinQuestionsand Answers

WHAT IS THIS BOOK ABOUT?

This book is a collection of algorithmic puzzles—puzzles that involve, explicitly or implicitly, clearly defined procedures for solving problems. It is a unique collection of such puzzles. The book includes some old classics, which have become a part of mathematics and computer science folklore. It also contains newer examples, some of which have been asked during job interviews at major companies. The book has two main goals: • To entertain a wide range of readers interested in puzzles • To promote development of high-level algorithmic thinking (with no computer programming), supported by a carefully developed list of general algorithm design strategies and analysis techniques Although algorithms do constitute the cornerstone of computer science and no sensible computer programming is possible without them, it is a common misconception to equate the two. Some algorithmic puzzles predate computers by more than a thousand years. It is true, however, that the proliferation of computers has made algorithmic important in many areas of modern life, from hard and soft sciences to art and entertainment. Solving algorithmic puzzles is the most productive and definitely most enjoyable way to develop and strengthen one’s algorithmic thinking skills.

WHOM IS THIS BOOK FOR?

There are three large categories of readers who should be interested in this book: • Puzzle lovers • People interested in developing algorithmic thinking, including teachers and students • People preparing for interviews with companies giving puzzles as well as people conducting such interviews All we have to say to puzzle lovers is to reassure them that they could enjoy this collection as they would a collection not dedicated to any particular theme or type of puzzle. They will encounter a few all-time favorites, but, hopefully, will also find a number of little-known puzzle gems. No computing background ix Preface in Questions and Answers x nevee prahsapzl hni nata ouint t hwn an Showing employer. potential it. the an impress to to way way then solution attractive should the highly techniques actual a analysis be in and an strategies interested design in general more applying than in expertise are puzzle they a that approaches interviewee claim interviews offering during managers all, After puzzles techniques. analysis with and encounter, strategies design may algorithm tutorials they on concise provides puzzles also book of the Second, examples comments. and many solutions complete contains it First, ways. two those especially courses, problem-solving the for at puzzles. interest on of courses—both based be computing also topics. might of project book and teachers The exercises supplemental by level—as algorithmic used school main secondary be and to college introduction also good can a They view, our ideas. in provide, they tutorials, the can Puzzles strategies. analysis deficiency. and important language design this computer general rectify a have applying of students of terms science instead in computer know problems they Even algorithmic level. about think abstract to more tendency a a on think effort to more force solver put puzzles algorithmic to a Second, willing exercises. routine normally doing is in than two person them for solving a into skill and almost important fun, this are for mastering puzzles skill for First, vehicle important in reasons. ideal very computers an are a of Puzzles thinking student. ubiquity algorithmic any justice: make some does world with today’s and educators, science computer solutions the references in ignore techniques simply analysis can and reader a strategies given. such design assumed; algorithm is specific it to in interest an even or ee fdfclya el h uze nteEse uze eto eur only require two section other the Puzzles in Easier problems few the a to in solutions Although puzzles mathematics. The school middle well. increasing in as puzzles the difficulty order of to tried difficulty. level have puzzles’ we the sections, three the gauging these in of divided each help Within have some readers we Difficulty, give Medium Puzzles—to Still, of Harder Puzzles students. and Puzzles, school sections—Easier stumped three middle occasionally into puzzles by been book’s solved have professors easily math puzzles pinpoint; by to hard is difficulty notwithstanding. qualities algorithms. of analysis sought have we book, criteria. the following the for satisfy puzzles that selecting puzzles In years. mathematical the of over thousands invented among puzzles fraction small BOOK? a constitute THE puzzles Algorithmic IN INCLUDED ARE PUZZLES WHAT st epepeaigfritriw,te hudfidtebo epu in helpful book the find should they interviews, for preparing people to As with Together study. individual for used be certainly can book this in puzzles The among word buzz a of somewhat become recently has thinking Algorithmic hr,w atdtepzlst u ierneo ifiut ees Puzzle levels. difficulty of range wide a run to those puzzles of the subjectivity wanted the we elegance, Third, and beauty or for design looking in were principle we general Second, some illustrate that puzzles wanted we First, xi Preface in Questions and Answers the approach the reader is expected not Solutions are provided to every puzzle. As a rule, they start with a short answer. Algorithms are described in free-style English, with no special formatting or Most comments point out a general algorithmic idea that the puzzle andMany its puzzle books do not indicate the puzzle sources. The reason usually Fourth, we have felt compelled to include a few puzzles because of their historical One more important comment needs to be made here. Many puzzles in this This is done to provide the readerhis or with her the own: last if opportunity the to reader’s solve answercan the disagrees stop with puzzle reading the the on one complete in solution the and book, try the to reader solve the puzzle again. pseudocode notations. The emphasisdetails. is Rewriting the on solutions theuseful in exercises ideas in a their rather own more right. than formal insignificant manner may, in fact,solution illustrate. provide Occasionally, they also includethe book references and to elsewhere. similar puzzles in given is that tryingauthor to of find a andecided joke. author to While of mention the there a earliestshould puzzle is sources keep is of a in the mind, akin lot however, puzzles toextensive that known of search trying we to for truth have us. to the not to The puzzles’ find conducteddifferent reader origin; anything this book. an doing close observation, that to would an we have resulted have in a very HINTS, SOLUTIONS, AND COMMENTS The book contains hints, solutions, andrarely comments for include every hints, puzzle. but Puzzle books wea see small them push as in athe a valuable right addition. puzzle. direction, Hints All still maysection. leaving the provide the hints reader are with a collected chance at to the solve end of the book in a separate to employ to solve thehave puzzles, excluded categories unless of explicitly puzzles stated suchto as otherwise. be solved Therefore, and either we by cryptarithms, exhaustive which search/backtracking have orin by the some ingenious specific insight data given inpuzzles the based puzzle. on We some have physical also objectsthe decided that Chinese are against Rings and not inclusion Rubik’s very of Cube. easy to describe, such as sections do use proofs by induction,suffice for high solving school all the mathematics book’s should, puzzles. in Inand addition, general, simple topics such recurrence as binary relations numbers aredoes not briefly mean, reviewed of course, in that the all theespecially second puzzles those in tutorial. the at This book the are easy. end Somedoes of of the them— not last lie section—are in trulyintimidated hard. some by But them. sophisticated their mathematics, difficulty and the reader should notimportance. Finally, be we only included puzzlesdevoid with of clear any statements tricks and such as solutions intentional ambiguity, word play, and so on. book can be solvedexplained by in exhaustive the book’s search first or tutorial.) backtracking. It is (These strategies are Preface in Questions and Answers xii [email protected] 2011 May Levitin Maria Levitin Anany of feats amazing and of puzzles. book’s beauty the in of delight many our behind ingenuity share human will they hope also We useful. serve also can hints. help and additional technique should of or list index puzzles strategy a This specific as indicating analysis. a on of index problems type locate an a to reader contains or the strategy book design the particular a index, on standard BOOK? based a THE to IN addition In INDICES TWO THERE the of ARE refresher WHY concise a as them use algorithms. of might analysis and reader design the a in examples. ideas such fundamental puzzle time, for science possibly, computer same except, a the new, with At anything reader there A find hardly readers. will of degree variety wide a for comprehensible use hints tutorials. few the a in explained easier and terminology much comments, special puzzles solutions, some the Besides, solving useful. these make more in can importantly, discussed they and, topics that the question of no knowledge is any there without tutorials, solved be can for book strategies the puzzles all general in almost Although on analysis. algorithm examples, for puzzle techniques and with design algorithm tutorials, two includes ABOUT? book The TUTORIALS TWO THE ARE WHAT ecnld ihahp htteraeswl n h okbt noal and enjoyable both book the find will readers the that hope a with conclude We them make to possible level elementary most the on written are tutorials The Acknowledgments

We would like to express our deep gratitude to the book’s reviewers: Tim Chartier (Davidson College), Stephen Lucas (James Madison University), and Laura Taalman (James Madison University). Their enthusiastic support of the book’s idea and specific suggestions about its contents have certainly been very helpful to us. We are also thankful to Simon Berkovich of the George Washington University for several discussions of the puzzle topics and for reading a portion of the book’s manuscript. Our thanks go to all the people at the Oxford University Press and their associates who worked on the book. We are especially grateful to our editor, Phyllis Cohen, for her ceaseless efforts to make the book better. We are also thankful to the editorial assistant, Hallie Stebbins, the book’s cover designer, Natalya Balnova, and the marketing manager, Michelle Kelly. We appreciate the work of Richard Camp, the book’s copy editor, as well as the efforts of Jennifer Kowing and Kiran Kumar who supervised the book’s production.

xiii This page intentionally left blank ListofPuzzles

TUTORIAL PUZZLES

The list below contains all the puzzles in the book’s two tutorials. The puzzles are listed in the order of their appearance. The page numbers indicate locations of the puzzles; their solutions are given directly in the tutorials following the puzzle statements.

Magic Square 4 The n-Queens Problem 6 Celebrity Problem 8 Number Guessing (Twenty Questions) 9 Tromino Puzzle 10 Anagram Detection 11 Cash Envelopes 12 Two Jealous Husbands 12 Guarini’s Puzzle 14 Optimal Pie Cutting 15 Non-Attacking Kings 16 Bridge Crossing at Night 17 Lemonade Stand Placement 18 Positive Changes 19 Shortest Path Counting 20 Chess Invention 23 Square Build-Up 24 25 Domino Tiling of Deficient Chessboards 28 The Königsberg Bridges Problem 29 Breaking a Chocolate Bar 30 Chickens in the Corn 30

xv List of Puzzles xvi 14. 18. 17. 13. 12. 27. 26. 25. 24. 23. 22. 21. 20. 19. 11. 10. 15. 16. hsls otisal10pzlsicue ntemi eto ftebo.The comments, book. with the solution of and section hint, puzzle, main respectively. the the of in locations included indicate numbers puzzles page 150 all contains list This PUZZLES SECTION MAIN 9. 8. 7. 6. 5. 4. 3. 2. 1. onrt-onrJourney Corner-to-Corner A Reach King’s A emOrdering Team Dissection Square Descent Sum Maximum Numbering Page rmn Tilings Tromino Reassembly Chessboard aigPancakes Making Paths Blocked Tiling Questionable h csa Game Icosian The Rank the Find Alive Be to Time Best The Colorings Chessboard Problem Flag National Polish Coins Fake of Stack A Coins Eight Among Fake A Arithmetic Mental Assembly Puzzle Jigsaw Night at Crossing Bridge Count Finger a Predicting o n ounExchanges Column and Row erigSoldiers Ferrying etnl Dissection Rectangle Selection Glove Cabbage a and Goat, a Wolf, A 7 3 100 73, 37, 4 3 90 73, 34, 6 3 93 73, 36, 7 3 97 73, 37, 2 2 83 72, 32, 5 3 92 73, 35, 6 3 94 73, 36, 2 2 84 72, 32, 6 3 93 73, 36, 7 3 96 73, 37, 8 3 100 73, 38, 4 2 87 72, 34, 4 3 90 73, 34, 2 2 83 72, 32, 4 3 89 73, 34, 7 3 98 73, 37, 3 2 87 72, 33, 6 3 95 73, 36, 5 3 91 73, 35, 3 2 86 72, 33, 7 3 99 73, 37, 3 2 85 72, 33, 4 3 88 73, 34, 3 2 85 72, 33, 6 3 94 73, 36, 7 3 97 73, 37, 2 2 82 72, 32, xvii List of Puzzles 45, 75, 124 43, 74, 116 40, 74, 106 46, 75, 126 45, 75, 125 46, 75, 128 44, 75, 121 42, 74, 115 40, 74, 106 43, 74, 118 39, 74, 103 43, 74, 118 41, 74, 111 39, 74, 105 43, 75, 119 44, 75, 120 42, 74, 115 45, 75, 124 43, 74, 117 43, 74, 117 46, 75, 126 41, 74, 110 41, 74, 112 45, 75, 125 45, 75, 123 40, 74, 107 38, 74, 101 39, 74, 105 42, 74, 114 40, 74, 109 44, 75, 122 -Counters Problem n Lighter or Heavier? Number Placement Limited Diversity Board Walks Four Alternating Knights The Circle of Lights The Other Wolf-Goat-Cabbage Puzzle Magic and Pseudo-Magic Coins on a Star Three Jugs 2 Tetromino Tiling Magic Square Revisited Cutting a Stick The Three Pile Trick Single-Elimination Tournament Figure Tracing Sorting Once, Sorting Twice Fibonacci’s Rabbits Problem A Knight’s Shortest Path Tricolor Arrangement Exhibition Planning Cutting a Rectangular Board Odometer Puzzle Lining Up Recruits McNugget Numbers Fake-Coin Detection with a Spring Scale Missionaries and Cannibals Counting Triangles Last Ball Missing Number 58. 44. 57. 43. 54. 55. 56. 36. 39. 40. 41. 42. 48. 33. 34. 35. 37. 38. 53. 49. 52. 29. 30. 31. 50. 51. 32. 28. 45. 46. 47. List of Puzzles xviii 89. 88. 87. 86. 85. 84. 83. 82. 81. 80. 79. 78. 77. 76. 75. 74. 73. 72. 71. 70. 69. 68. 67. 66. 65. 64. 63. 62. 61. 60. 59. one Exchange Counter od n Frogs and Toads pieDw Glasses Upside-Down II Spreading Rumor I Spreading Rumor Sorting Pancake Hanoi of Tower Restricted Up Heads Revisited Problem Celebrity Tour Prince’s The Doors Locker tagtToioTiling Tromino Straight erhn o Pattern a for Searching Rook Efficient Inspections Station Gas ieSelection Site Chase Rooster II Cells Marking I Cells Marking I Pairs into Jumping hp nSectors on Chips ii Sum Digit vrgn Down Averaging Number Remaining Guessing Code Octagons Creating Minuses and Pluses Coins Up Picking Diagonal a on Checkers qaigaCi Triangle Coin a Squaring aso w Colors Two of Hats 2 7 150 77, 52, 8 6 137 76, 48, 0 6 143 76, 50, 1 7 148 77, 51, 1 6 145 76, 51, 9 6 141 76, 49, 7 6 135 76, 47, 8 6 139 76, 48, 9 6 140 76, 49, 2 7 153 77, 52, 3 7 157 77, 53, 8 6 137 76, 48, 8 6 138 76, 48, 7 6 132 76, 47, 1 7 148 77, 51, 3 7 159 77, 53, 7 6 134 76, 47, 3 7 155 77, 53, 6 5 129 75, 46, 7 6 133 76, 47, 8 6 136 76, 48, 3 7 156 77, 53, 8 6 139 76, 48, 3 7 157 77, 53, 1 6 146 76, 51, 0 6 144 76, 50, 7 6 131 76, 47, 1 6 147 76, 51, 6 5 129 75, 46, 2 7 151 77, 52, 1 7 149 77, 51, xix List of Puzzles 54, 77, 161 57, 78, 174 62, 79, 196 62, 79, 192 57, 78, 175 60, 78, 183 55, 77, 165 60, 78, 186 55, 77, 167 62, 79, 195 54, 77, 160 59, 78, 178 55, 78, 169 56, 78, 170 59, 78, 180 59, 78, 181 55, 77, 164 59, 78, 181 55, 77, 166 57, 78, 172 61, 79, 188 54, 77, 162 59, 78, 183 56, 78, 171 58, 78, 178 57, 78, 173 60, 78, 187 61, 79, 188 61, 79, 190 58, 78, 176 62, 79, 193 Dominoes n The Fox and the Hare The Longest Route Domino Tiling Revisited Crossing Dots Double- The Chameleons Inverting a Coin Triangle Coin Removal Bachet’s Weights Bye Counting One-Dimensional Solitaire Six Knights Colored Tromino Tiling Penny Distribution Machine Jumping to the Other Side Pile Splitting The MU Puzzle Turning on a Light Bulb Room Painting The Monkey and the Coconuts Reversal of Sort A Knight’s Reach The Game of Topswops Palindrome Counting Horizontal and Vertical Dominoes Hitting a Battleship Tiling a Staircase Region Seating Rearrangements Trapezoid Tiling Searching a Sorted Table Max-Min Weights 99. 97. 98. 91. 93. 96. 90. 92. 94. 95. 107. 108. 112. 114. 109. 110. 111. 113. 115. 116. 117. 118. 119. 120. 103. 104. 105. 106. 101. 102. 100. List of Puzzles xx 122. 121. 127. 126. 125. 124. 123. 137. 136. 135. 134. 133. 132. 131. 130. 129. 128. 142. 141. 138. 147. 146. 145. 144. 143. 140. 139. 150. 149. 148. alaetPacification Parliament Testing Super-Egg h ngtsTour Knight’s The Fairly Cake a Dividing 7 in 5 Sorting Cutting Chain Problem Flag National Dutch upn noPisII Pairs into Jumping Spy a Catching Pairings Different Coloring Point Life of Game The Army Solitaire The Puzzle Counter Tait’s Wine Poisoned eesPuzzle Reve’s Switches Security wleCoins Twelve Problem Josephus The Sharing Candy aswt Numbers with Hats Target Moving a Hitting Puzzle Fifteen The Squares Killing Chessboard Infected The Table Round Arthur’s King ugra Solitaire Bulgarian Spreading Pebble Freedom for Coin One n Qen rbe Revisited Problem -Queens 4 9 202 79, 64, 4 0 207 80, 64, 7 0 225 80, 67, 3 9 199 79, 63, 7 0 220 80, 67, 6 0 217 80, 66, 6 0 215 80, 66, 4 0 209 80, 64, 8 1 227 81, 68, 5 0 214 80, 65, 4 0 205 80, 64, 9 1 236 81, 69, 6 0 216 80, 66, 3 9 197 79, 63, 4 9 204 79, 64, 8 1 229 81, 68, 0 1 238 81, 70, 5 0 211 80, 65, 9 1 232 81, 69, 8 1 227 81, 68, 7 0 219 80, 67, 5 0 209 80, 65, 4 9 203 79, 64, 9 1 234 81, 69, 7 0 223 80, 67, 3 9 198 79, 63, 9 1 231 81, 69, 7 0 221 80, 67, 3 9 199 79, 63, 7 0 222 80, 67, xxi List of Puzzles and books on recreational SAID WHAT? (“The Book of Calculation”), one of the How Would You Move Mount Fuji? Microsoft’s Scientific American Liber Abaci the classic book on problem solving How To Solve It, Leonardo of Pisa a.k.a. Fibonacci (1170–c1250), a remarkable Italian math- Carl Friedrich Gauss (1777–1855), a great German mathematician (1914–2010), an American writer, best known for his William Poundstone, the author of George Pólya (1887–1985), a prominent Hungarian mathematician, the author ematician, the author of mathematics “Mathematical Games” column in If I have perchanceindulgence, omitted since anything there more is or nothings. less one proper who or is blameless necessary, and I utterly beg provident in all It is not knowledge, but thethere, which act grants of the learning, greatest not enjoyment. possession but the act of getting There is no better way tointo relieve the a tedium course, than topics by strongly injectingsurprise. recreational tinged topics with elements of play, humor, beauty, and Solving problems is a practicalpractical skill skill like, by let imitation and us practice. say, swimming. We acquire any The man with a hammer seesis every the problem algorithm. as a nail. Our age’s great hammer THE EPIGRAPH PUZZLE: WHO Match the following quotations with the authors listed below: most consequential mathematical book in history of Cult of the Puzzle: HowThinkers the World’s Smartest Companies Select the Most Creative This page intentionally left blank Algorithmic Puzzles This page intentionally left blank 1Tutorials

GENERAL STRATEGIES FOR ALGORITHM DESIGN

The purpose of this tutorial is to briefly review a few general strategies for designing algorithms. While these strategies are not all applicable to every puzzle, taken collectively they provide a powerful tool kit. Not surprisingly, these strategies are also used for solving many problems in computer science. Therefore, learning to apply these strategies to puzzles can serve as an excellent introduction to this important field. But before we embark on reviewing major algorithm design strategies, we need to make an important comment on two types of algorithmic puzzles. Every algorithmic puzzle has an input. An input defines an instance of the puzzle. The instance can be either specific (e.g., find a false coin among eight coins with a balance) or general (e.g., find a false coin among n coins with a balance). When dealing with a specific instance of a puzzle, the solver has no obligations beyond solving the instance given. In fact, it might be the case that other instances of the puzzle do not have the same solution or even do not have solutions at all. On the other hand, specific numbers in a puzzle’s statement may be of no significance whatsoever. Then solving the general instance of the puzzle could be not only more satisfying but, on occasion, even easier. But whether a puzzle is presented by a specific instance or given in its most general form, it is almost always a good idea to solve a few small instances of it anyway. On rare occasions the solver might be misled by such investigation, but much more often it can provide useful insights into the puzzle given.

3 Algorithmic Puzzles 4 u ftenmesi ahrw oun n onrt-onrdaoa stesame the is diagonal corner-to-corner 1.1). and (Figure column, row, each in numbers the of sum n oo ni h atnme spae nteol ncuidcl ftetable. the 2, of place cell 9 unoccupied to only = ways the 9! in eight are placed by is there followed 9 Hence, number 1, last place the to until on ways so with nine and ending are and somewhere There 1 9. the the placing with placing starting time, a at number one with nteclso h 3 the of cells the in ai Square Magic constructing of but problem the human consider a example, an for a As only well. not as computer inappropriate a approach for with often the exponentially least making at size, grows number problem processed the be the rule, to a need as that inefficiency: candidates its solution most of is The strategy. search this exhaustive applying of by found limitation exhaustive be important will applying solution a computer) in that a expectation to required the opposed (as in the person typically a to to offered is solution rarely are ingenuity puzzles a Therefore, search. until Little solutions found. candidate is possible problem all tries simply that strategy by solved be can puzzles many Theoretically, Search Exhaustive IUE1.1 FIGURE ftecmo u seult 5adta utb u ttecne cell center the at put be must 5 that and 15 to equal the is (see sum common the of hand. by do same. to each the impossible are for clearly sums is checking, diagonal work and and of amount column, table This row, the its in all possible whether 9 362,880 arrangements, to the all 1 of from generating integers imply distinct would of search arrangements exhaustive by problem this factorial lentvl,oecntk datg fsvrlkonagrtm o constructing for algorithms known several of advantage take can one Alternatively, ai square magic o aywy r hr ofilsc al?Ltu hn ftetbea filled as table the of think us Let table? a such fill to there are ways many How culy ti o ifiutt ov hspzl ypoigfis httevalue the that first proving by puzzle this solve to difficult not is it Actually, o h rdc fcneuieitgr rm1to 1 from integers consecutive of product the for , ai qaeRevisited Square Magic 3 × ilthe Fill fodr3. order of al ob le ihitgr hog ofr ai square. magic a form to 9 through 1 integers with filled be to table 3 × 3 al.(ejs sdtesadr notation, standard the used just (We table. 3 × · 3 8 al ihnn itntitgr rm1t ota the that so 9 to 1 from integers distinct nine with table · ... ? ? ? · uze(2)i h anscino h book). the of section main the in (#29) puzzle 6,8 ast rag h ienumbers nine the arrange to ways 362,880 = 1 ? ? ? xasiesearch exhaustive ? ? ? n )Teeoe solving Therefore, .) aproblem-solving —a n ! , called n 5 Tutorials to tree remaining . The root of as small as 5. any 3 table (see the n × of these numbers, state-space tree which are especially efficient for odd , 3 (the only node without a parent) on the ≥ n root , and hence it would take a computer making 10 trillion 25 10 · 5 (nodes without children) on or closer to the bottom of the . 1 is an important improvement over the brute-force approach of example above) can be obtained as ! leaves ) 2 Typically, backtracking involves undoing a number of wrong choices—the It is convenient to interpret a backtracking algorithm as a process of constructing Backtracking ’s (e.g., [Pic02]). Of course, these algorithms are not based on exhaustive search: a state-space tree corresponds toconsider the start the of root a to solutionthe construction be first process; on level we of the the zero tree—correspond level to possible of choices the of tree. the first The component root’s children—on smaller this number, theworst-case faster scenario the a backtracking algorithm algorithm finds maycandidate end solutions a as up an solution. generating exhaustive Although all search, this the in rarely same happens. the a tree that mirrors decisions being made. Computer scientists use the term component need to be considered. In this case,the the last algorithm backtracks component to of replace thethat partially component. constructed solution with the next option for describe hierarchical structures suchA as tree family is usually treestop shown and and with organizational its its charts. diagram. This is nothingFor but a a backtracking convenient algorithm, such typographical a convention, tree however. is called a exhaustive search. Itsolutions provides while a making convenient itThe method possible main to for idea avoid generating is generating tosuch candidate partially unnecessary construct constructed candidates. candidates solutions as one follows: If componentcan a be at partially constructed developed a solution further time without andby violating taking evaluate the the problem’s first constraints, remainingis it legitimate no legitimate is option option done for for the the next next component, component. no If alternatives there for for which several algorithms are known. There are manysolution problems, candidates however, where do not formand a more set with fundamental, such difficulty a liesneed regular in to structure. be the The generated number second, and ofexponentially processed. with solution Typically, the candidates problem the size. that size Therefore, offor exhaustive very this search small is set instances practical grows of only such at problems. least Magic Square Indeed, (5 operations per second about 49,000 years to finish the job. the number of candidateto solutions consider the becomes exhaustive prohibitively search large algorithm even would for have a computer for n There are two majorlies in difficulties the in mechanics applyingproblems, of such exhaustive candidates generating compose search. a all well-structured Thearrangements possible set. of the For first solution first example, nine positive candidate candidates. one integers in For the cells of some the 3 Backtracking magic squares of an arbitrary order Algorithmic Puzzles 6 akrcigt atclrproblem. particular a to backtracking to backtracking by them for parent. searching leaf’s continues the algorithm the for, need solutions searched other be if stops; to algorithm the to suffices, solution solution a single provides considers a leaf If and a problem. the of node, kind second nonpromising The component. the that of for choice parent another the to backtracking by solution takec te ybigi h aeclm,rw rdiagonal. or row, column, same the in being by other each attack eada n eas hr sn cetbepsto ntetidclm for column third the to proves in This position 2. acceptable column no and is 3 there row trying because in after square end 2, the dead queen 2), position a (3, place acceptable be first square we the is in Then which column, 1. it, second the for column of 2 of and 1 1 rows row unsuccessfully in is which position, oun l ene od st sinarwfrec ue ntebadsonin shown board the on queen each own for its row in a placed assign 1.2. to be Figure is to do has to queens need four we the all of column, each Since backtracking. by it solve h -uesProblem n-Queens The said is tree (the node the terminates be node to algorithm particular a backtracking that a establishing nonpromising, After solution. is a first to The lead kinds. cannot two that of candidates be can Leaves on. so the kind—called and Their of solution, construction). choices a square possible of magic to component the level—correspond second in second 1 the contain on to nodes cell children—the the (e.g., solution a of IUE1.2 FIGURE sn ouinfor solution no is h olwn xml saprnilfvrt o hwn napiainof application an showing for favorite perennial a is example following The esatwt h mt or n hnpaeqen1i h rtpossible first the in 1 queen place then and board empty the with start We For pruned n = or o h -uesproblem. 4-queens the for Board 1 ,ude h eiinrgrigtels opnn ftecandidate the of component last the regarding decision the undoes ), opoiignodes nonpromising , h rbe a rva ouin n ti ayt e htthere that see to easy is it and solution, trivial a has problem the n = and 2 Place 4 3 2 1 n n ueso an on queens 1 Q = or .S e scnie h -uespolmand problem 4-queens the consider us let So 3. edends dead Q 2 3 Q n crepn oprilyconstructed partially to —correspond × n 4 Q hsbads htn w queens two no that so chessboard 7 Tutorials n G o Q i Q t Q u I Q l Q o s Q a Q . H 2 X 3 X Q F Q 1820 1 X 2 X = Q 13 · 1 X 2 · 14 · 3 4 X · 15 4 3 X A · 4 X 16 3 X D Q E = ! Q Q 2 X 4) Q Q ! − 1 X 1 X 16 (16 B ! 4 4 X Q 3 X C Q State-space tree of finding a solution to the 4-queens problem by 4 board, the number of such placements is 2 X Q × 1 X 2 X How much faster is this solution by backtracking compared to exhaustive search? If other solutions need to be found (there is just one other solution to the 1 X backtracking. X denotes an unsuccessfulThe attempt letters above to the place nodes a show the queen order in in the which the indicated nodes row. are generated. If we are to consider all possible placements ofof four the queens on 4 four different squares 4-queens problem), the algorithm canwhich simply it resume stopped. Alternatively, its one operations can at use the the board’s leaf symmetry for at this purpose. FIGURE 1.3 queen 3. Therefore, the algorithm backtracks and putsposition queen (4, 2 2). in Then the queen next 3 possible isend. placed The at algorithm (2, then 3), backtracks which all provesQueen the to 2 way be then to another queen goes dead 1 to and (4,solution moves to 2), it the queen problem. to 3 The (2, state-space to 1). tree (1, of 3), this search and is queen given 4 in Figure to 1.3. (3, 4), which is a Algorithmic Puzzles 8 either mathematicians by ssterae odsg uhfse loih o the for algorithm faster much a design to In reader for. the strive asks to expected is reader the algorithm particular, efficient more a is there however, If n st h general the reflections. and to rotations by distinct, As twelve qualitatively basic the are from which obtainable of 80 remaining twelve the 92, with is problem 8-queens the to solutions ihi ilfidawat fifrainb,sy olwn h eeecsadlnsi h Wikipedia the in links and references the following say, by, science).” information (computer of “recursion on wealth article a find will it with hl for while 8 Decrease-and-Conquer for solutions of number the example, For of set given a from interest, of choose not to is ways which of of number order the for formula general (The 1 Problem Celebrity solved be to enough small becomes it directly. until instances diminishing its of sequence a such a found, to Once naturally instance. smaller leads its relationship to a solution a and problem given a to solution The ifrn os h ubro hie rp o4 to drops choices of number the rows, different icvrd ti nw htti ubrgosvr atwt h au of value the with fast very grows number this that known is It discovered. ovnetfruafrtenme fsltosfra arbitrary an for solutions of number the for formula convenient ut aaebe twudntb h aefrlre ntne ftepolm For problem. the of 8 instances regular larger a for for case example, the be not would it manageable, quite uesi ifrn oun,tettlnme fslto addtsdcessto decreases candidates solution of number 4 total the columns, different in queens ooybti nw yeeyoyes.Tets st dniyaclbiyb only by celebrity person?” a this identify know you to “Do is form: following task the The of people else. to everybody questions asking by known is but nobody nw ,rmv rmtermiigpol h a eaclbiy fAdoes A if celebrity; If a B. be knows can she who or people he remaining whether the A from ask A and remove B, B, and knows A A say, group, the from people two != 4 h oino a of notion The epe h rbe a esle ytefloigdces-yoealgorithm. decrease-by-one following the by solved be can problem the people, n suigfrsmlct htaclbiyi nw oeitaogagvngopof group given a among exist to known is celebrity a that simplicity for Assuming aypzlsi hsbo a esle ybctakn.Frec fthem, of each For backtracking. by solved be can book this in puzzles Many h edrmgtb neetdt nwta h oa ubro different of number total the that know to interested be might reader The = = decrease-and-conquer 40 256 1 k n , 1 , 320. n htoepro svcosyaclbiyb h ento.If definition. the by celebrity a vacuously is person one that . eei nexample. an is Here or h n The n fw d otelte h osritta h uesms lob in be also must queens the that constraint the latter the to add we if And = C 2tersetv ubr r 420ad1787. and 14,200 are numbers respective the 12 recursion ( - n uesPolmRevisited Problem Queens , eert mn ru of group a among celebrity A n k combinations qen rbe,i a ouinfrevery for solution a has it problem, -queens ) , soeo h otiprati optrsine h edrunfamiliar reader The science. computer in important most the of one is is × k hsbad h ubro uhslto addtsis candidates solution such of number the chessboard, 8 taeyi ae nfidn eainhpbtena between relationship a finding on based is strategy ! ( n n − ! k ) ! eusv algorithm recursive )I ecnie nytepaeet ihthe with placements the only consider we If .) of n bet taken objects n #4)i h anscino h book the of section main the in (#140) = 0i 2,o hc 2aedistinct, are 92 which of 724, is 10 != n epei esnwoknows who person a is people hc eue h rbe to problem the reduces which , 24 k tatm n eoe by denoted and time a at n . n hl h atnme is number last the While qen problem. -queens ifrn bet,called objects, different k ifrn bet,the objects, different n n ≥ n > a been has u no but 4 1 , select n . 9 Tutorials For . x puzzle For example, . which is the x ,  2 / n  If the answer is “no,” 2 Ferrying Soldiers if the answer is “yes,” the is the most common case In either case, the algorithm ; . 2 n / 1 people who can be a celebrity. n  1to − n . For a specific example, see the first variation of the decrease-and-conquer + 2 / is the largest integer smaller than or equal to decrease-by-one n , x  1,000,000, the algorithm requires no more of ) Determine a selected integer in the range from = puzzle (#3) in the book’s main section. is the smallest integer larger than or equal to n , floor x to an instance of the same problem of about half the Although n (#10) in the main section of the book provides another . 1 . 2 strategy is to partition a problem into several smaller incremental approach 2 rounded up to the nearest integer. − , called the /  n = n x 2   . of a real number Twenty Questions 2 ( decrease-by-constant-factor Rectangle Dissection 2 and = ceiling 2  = 3 . 2  3 and divide-and-conquer , inclusive, by asking questions with yes/no answers. , called the n  = Since this algorithm reduces the size of an instance (the range of the numbers In general, a smaller instance in the decrease-and-conquer paradigm need not As an easy exercise, the reader may want to solve the A Fake Among Eight Coins The fastest algorithm for this problem asks a question that reduces the size of It should be noted that sometimes it is easier to exploit a relationship between x 3 .  2 subproblems (usually of the same or related type and ideally of about the same standard notation for that still can contain the selected number)amazingly by about fast. half For on each example, iteration, for it works size of the original instance. Repeating this step1 until solves the the instance problem. size is reduced to selected number is among the integers the selected number is among the integers 1 to necessarily be of size (#4) in the main section of the book. than 20 questions! Asreduce fast the instance as size it by a is, larger an factor, say, algorithm 3. would be evenillustration faster of the if it could of size reduction, there are examplesa of particularly size fast reduction algorithm by if a larger wefactor, amount. manage for We reducing example, get an by instance half, sizealgorithm on by arises in a each the constant iteration. following well-known A game. well-known example of such an the set containing the answer by about halfquestion on can each be iteration. For whether example, the the selected first number is greater than reduced the problem of size example,  2 Divide-and-Conquer The Number Guessing 1to not know B, remove B from this group.the Then same solve method) the for problem the recursively remaining (i.e., group by of larger and smaller instances bottom up. Thissmallest means possible solving instance, first the then puzzle for foris the the sometimes next called larger the one, and so on. This method strategy and can serve as a good exercise here. solution of the Algorithmic Puzzles 10 ftebadsurs rmne hudcvraltesursecp h isn one missing overlaps. the no except with squares the exactly all any cover be should Trominoes can squares. square board missing the The of squares. adjacent three by formed tiles L-shaped are n lcsatoioa h etro h or nsc a htteproblem’s the that way a such in board the of size center of the instance at tromino a places upolm htne ob ovdo ahse:svrli divide-and-conquer smaller in of several algorithms. step: decrease-and-conquer number in each the one on just design in and solved distinct algorithms, lies be as to two it need the that consider between subproblems to difference better crucial a is The as it strategy. above) divide-and-conquer, of (discussed case decrease-and-conquer special consider people some Although rmn Puzzle Tromino many strategy. this not illustrates example, perfectly are well-known that a however, there is Here Surprisingly, algorithms. divide-and-conquer science. by solvable computer puzzles in a get problems to important solutions algorithms efficient for their many underlines combine strategy This necessary, problem. if original the then, to solution and them, of each solve size), IUE1.4 FIGURE qaegnrtdb ti oee ihasnl tromino. single a with covered is it by generated square ors npriua,abadmyne ob iie nosborsta r not are see that examples, such subboards Problem For into given. divided board the be of to versions need smaller same necessarily may the board involving problems a of some particular, For instances in however. smaller case, boards, the represent be always they not need example, This above problem. the in as because, exercise. useful but quick a as algorithm iieadcnuralgorithm. divide-and-conquer − h edrmywn ofiihtetln fte8 the of tiling the finish to want may reader The that algorithm divide-and-conquer recursive a by solved be can problem The n oecmetnest emd bu h iieadcnurstrategy. divide-and-conquer the about made be to needs comment more One otdvd-n-oqe loihsslesalrsbrbesrecursively subproblems smaller solve algorithms divide-and-conquer Most Fgr .) h loih tp fe vr 2 every after stops algorithm The 1.4). (Figure 1 #7 and (#37) is tpi rmn iigo 2 a of tiling tromino in step First oe a Cover n srdcdt orisacso h aepolm aho size of each problem, same the of instances four to reduced is tagtToioTiling Tromino Straight 2 n × 2 n or isn n qaewt ih rmne,which trominoes, right with square one missing board #8 ntemi eto ftebook. the of section main the in (#78) n × 2 n × or ihu n qaeb a by square one without board qaei iue14b this by 1.4 Figure in square 8 × einwt n missing one with region 2 2n-Counters 11 Tutorials 8 2 3 2 · · —is , and 0 1 0 2 + + · 9 3 1 2 3 · · puzzle (#43), + 0 0 1 2 + + · 4 10 0 3 2 · · + 1 1 representation change 2 2 + = · 5 3 1 · Number Placement + , in which an instance of a given 1 In the binary and ternary systems, 3 . + 2 0 · 6 10 3 1 · · because 1069 9 1 + 2 4 + = 2 1 · 10 0 · problem reduction + 6 is a well-known approach to problem solving that is 5 + [Ben00, pp. 15–16]. 2 2 · 10000101101 1 10 = because 1069 —solves a problem by first transforming an instance given · While a decimal number is composed of some of 10 digits 3 Anagrams are words that are composed of the same letters; for + 10 0 . 0 6 3 + 2 · · 3 1 0 10 1110121 · + + 1 = 1 7 3 2 = Programming Pearls 10 · transform-and-conquer · 2 0 An efficient algorithm for this problem works in two stages. First, it assigns each As an exercise, the reader is invited to solve the As our first example, let us consider a puzzle-like problem from Jon Bentley’s Another occasionally useful type of representation change is to employ binary or 1069 (0 through 9), there areand only there are two three possible possible digits digits (0,integer 1, in has and a a 2) unique in binary a representation number ternary in number. either (0by Every of repeatedly and decimal these dividing 1), systems, which the can integer beparticularly by found important 2 because and it 3, has respectively. provedimplementation. to The be binary most system convenient is for computer an integer is representedFor as example, 1069 a combination of powers of 2 and 3, respectively. word a “signature” obtained by sorting its letterssorts (representation the change) file and in then alphabetical order ofinstance the simplification) signatures to (sorting put data anagrams is next a to special each case other. of + + example, the words “eat,” “ate,” and “tea” areall anagrams. sets Devise of an algorithm anagrams to in find a large file of English words. Anagram Detection Transform-and-Conquer The based on the ideain of the transformation. transformation A stage, it problemthat, is is for modified solved or one in transformed reasonsecond, two into or another conquering stages. problem another, First, stage, issolving, it one more is can amenable identify solved. three toinstance varieties In simplification solution. of our this Then, strategy. realm in Theinto first another of the instance variety—called of algorithmic the same problem the problem problem with some easier special to property solve. that Thebased makes second on variety—called the transformationthat of is a more problem’s conducive input tothe to an transformation a efficient strategy algorithmic is different solution. representation The third variety of book problem is transformed into an instance of a different problem altogether. ternary representation of the problem’s input.with Just in this case important the topic, reader ispositional here system, unfamiliar which is most of a the world one-paragraph has beenyears, introduction. using for an the In last eight integer the hundred is decimal represented1069 as a combination of powers of 10, for example, which exploits the same idea. Algorithmic Puzzles 12 Weights 84]. p. [Pou03, book Poundstone’s W. in mentioned problem the of instance rmoevre oaohr ntefre ae h rp ssi obe to said is graph the case, former the In another. to vertex one from respectively, called, are lines and and points The them. of some connecting lines A graphs. respectively. system, ternary nteltrcs,i scle a called is it case, later the in elkonpuzzle. well-known a to vertex initial-state the from path a vertex. kind.) about goal-state latter question the the to of problem vertices the reduces several a represents be called another might is graph (There while a problem. state, Such the initial of an state represents goal vertices a states. graph’s the the between the of transitions of permitted states One indicate possible edges represent and typically question, graph in a problem of vertices games, and puzzles to oeofniewrigt oa’ om [Had92]. norms today’s to wording offensive more titled Young Latin, in problems mathematical of hn49cnb banda obnto ftepwr f2: of powers the of combination a as obtained be can 489 than +···+ (1 as given course. of be allowed, can is inclusive, change No $1000, and envelopes? $1 these of between combination amount some any that so envelops 10 Envelopes Cash 3 complicate presence To the time. in be a can at wife people no two that require than and more jealous no are husbands hold both can matters, that boat a have They Husbands Jealous Two iedgtbnr ubrcnrpeeti 2 is represent can number binary digit nine compose coefficients oeta h ouint h uzei o nqefrsm amounts some for unique not is puzzle the to solution the that Note obnto ftefis ie h atrgvnb h iayrpeetto of representation binary the by given latter the nine, first the of combination a 0 amount h lsi eso fti uzefrtreculswsicue nteeris nw collection known earliest the in included was couples three for puzzle this of version classic The ≤ odeecs o h edrwudb osletetovrin fthe of versions two the solve to be would reader the for exercise good A 1 put us Let an consider system, binary the of advantage takes that puzzle a of example an As ial,mn rbescnb ovdb rnfrigte noqetosabout questions into them transforming by solved be can problems many Finally, saseiceape e scnie mle ntneo eyodand old very a of instance smaller a consider us let example, specific a As + edges A ,wihi trbtdt luno ok(.3–0) eondmdea coa.I a even had It scholar. medieval renowned a (c.735–804), York of Alcuin to attributed is which ), 2  +···+ ≤ A uze(15,wihtk datg ftebnr n aito fthe of variation a and binary the of advantage take which (#115), puzzle b ftegah de a aen ietoso hmo a edirected be may or them on directions no have may Edges graph. the of graph 0 ewe 8 n 00 nlsv,cnb ersne s489 as represented be can inclusive, 1000, and 489 between 1;hne tcnb banda h otnso h et neoeand envelope tenth the of contents the as obtained be can it hence, 511; · ,weetecoefficients the where 1, , 2 o aeoetosn 1bls o a o itiuete among them distribute you can How bills. $1 thousand one have You a etogto safiiecleto fpit ntepaewith plane the in points of collection finite a as of thought be can 2 8 , ) 3 2 = 2 A .., ,... 8 olrblsi h et neoe n amount Any envelope. tenth the in bills dollar 489 srpeetto ntebnr ytm h ags nee a integer largest The system. binary the in representation ’s hr r w are ope h edt rs river. a cross to need who couples married two are There tt-pc graph. state-space 2 ietdgraph directed 8 olrblsi h rtnn neoe n 1000 and envelopes nine first the in bills dollar rpstoe dAuno Juvenes Acuendos ad Propositiones b 8 hs h rnfrainjs described just transformation the Thus, , 8 ,ora b + 7 .., ,... 2 7 digraph, +···+ b 0 r ihr0o .(These 1. or 0 either are o hr.I applications In short. for 1 = ( 2 rbest hre the Sharpen to Problems 9 b − 8 1 · A = 2 . + 8 undirected 511 + A A Bachet’s  smaller vertices b . where Any ) 7 · A 2 −  7 ; . 13 Tutorials 2 w denote denote i || ,W i 2 1 h w 1 ) The vertices h . 2 W 2 2 w 2 2 1 1 2 2 2 h h w W W W W 1 1 1 1 1 h puzzle. H H W W 2 w 1 2 2 2 2 1 1 w w 2 h 2 2 H H 1 1 2 W W w w 2 h respectively; the two bars h w h 1 2 2 2 w 1 w h w , w h 1 1 2 2 2 2 h w 2) H H H H , 1 1 1 1 1 2 H H H H h 2 2 2 = 1 1 h 2 w h 1 2 2 i h w 1 w 1 1 1 1 w 2 2 h w ( h 1 Two Jealous Husbands w h i 1 1 2 H H w W W h w w 1 1 w w 2 2 2 2 1 h W W W W 2 1 1 2 2 1 1 h h w 1 H H W W h 2 h 1 h 2 h 1 State-space tree for the h crossing the river instead of the second couple H 1 2 W w There are four shortest paths from the initial-state vertex to the final-state vertex, A state-space graph for this puzzle is shown in Figure 1.5, where H 1 1 w corresponding to the initial and final states are shown in bold. the husband and wife of couple each five edges long, in this graph. Specified by their edges, they are as follows: the river; the boat’s location, which definesby the the direction gray of oval. the (For next the trip,that sake is differ of shown simplicity, by the obvious graphH does index not substitutions include crossings such as starting with the first couple FIGURE 1.5 of the other man without her husbandsuch being constraints? present. Can they cross the river under Algorithmic Puzzles 14 oe ota h ht ngt r tteuprcresadtebakkihsare knights black the and corners upper corners. the bottom at of the number are at minimum knights the white in the knights the that switch so to moves is corners goal upper The two the 1.6). at (Figure are board knights the black of two the and corners, bottom two the at are a erahdfo etx1b ngtmvsa hw nFgr 1.7c—we Figure in shown picture. moves—as revealing they knight more order by much the a 1 in obtain circumference vertex will If, a from problem. along reached the vertices solving be the in place can much we help hand, to other seem the not on there.) does omitted at 1.7b is it Figure 5 knights, in number the of graph square any The by the reached (Since be cannot 1.7b. board Figure the of in center the shown the graph on squares the the the by obtain of represented positions we the squares board, mimicking the way between a in move vertices a the Placing make vertices. can knight a connects edge if an vertices which in two graph a of vertices by 1.7a) Figure in integers consecutive hw nFgr .cb itn n arig“utn”2 ,4 n oteopst ie ftegraph the of sides opposite the to 6 and as 4, graph 8, same 2, the “buttons” get it. carrying can “untangle” and one to lifting respectively, by strings, 1.7c and buttons Figure as in thought shown are graph the of edges and urn’ Puzzle Guarini’s 840. around from dating manuscripts chess Arab in Guarini found Paolo was to fact attributed in often but (1512) is which puzzle, For are following question. in vertices the puzzle consider the the into example, way insight important the an provide of can a selection plane the of good in placed a vertices significance, representing theoretical points no of has location graph specific a although Second, vertices. optimal substitutions) symmetric obvious crossings. river within five requiring each (to problem, this four to solutions are there Hence, 4 1.6 FIGURE 10 than graph more the have would example, puzzle For Cube transformations. Rubik’s and the states of states of because the infeasible number be representing large might task very the fact, a In of right. own an pose its can in puzzles sophisticated problem more algorithmic for graph state-space a of creation the First, kind. this uee Dd8 .20 aldsc rnfrainthe transformation a such called 230] p. [Dud58, Dudeney ti aua orpeettesurso h or nmee o ipiiyby simplicity for (numbered board the of squares the represent to natural is It The w oe edt emd bu ovn uze i rp representation. graph a via puzzles solving about made be to need notes Two isoaisadCannibals and Missionaries urn’ Puzzle Guarini’s hr r orkihso the on knights four are There . uze(4)cnb sda nte xrieof exercise another as used be can (#49) puzzle 4 3 ti la rmFgr .cta every that 1.7c Figure from clear is It × 3 hsbad h w ht knights white two the chessboard: utn n tig method strings and buttons fvertices if : 19 15 Tutorials , ,  n 2 / 3 4 1 . (b) )isa n is odd. h + n 8 9 n − = is even and n h + )if is equal to (  n ) h v (c)(c) 2 h / and + 2 1 n − 2if h   / n 2 n ( / 7 Guarini’s Puzzle 6 h n = is even and two solutions = h n = 1 v + 6 2if , / n  , inclusive. Since n 3 2 9 n + puzzle (#34) as an exercise in the / = n ) or up (denoted hv v  2 = = = vertical cuts, the total number of pieces / 2 n h 8 1 h v  (b)(b) + ) v Since the total number of cuts 1 . + between 0 and 7 Coins on a Star h 1) h ( 4 + + v horizontal and , the maximum is obtained for hv h h 1)( solves an optimization problem by a sequence of steps, each = What is the maximum number of pieces one can get by making 3 6 9 + h 1) is odd. + n v 2 5 8 if (a) Numbering of the board’s squares for 2 rounded down (denoted (a)(a) /  1)( n 2 / + n = h greedy approach ( h 4 7 1 If the pie is cut by We recommend solving the There are also puzzles that can be solved by reducing them to a mathematical = straight cuts in a rectangular pie, if each cut has to be parallel to one of the pie’s among all integer values of Hence, the puzzle has a unique solution Straightforward representation of thepuzzle’s graph. puzzle’s graph. (c) Better representation of the quadratic function of (which can be considered symmetric) problem such as solving anfunction. Here equation is or an example finding of the such a maximum puzzle. or minimum of a graph unfolding method. for The Greedy Approach v the problem is reduced to maximizing Optimal Pie Cutting sides, vertical or horizontal? n FIGURE 1.7 legitimate move of a knight preserves the knights’and relative ordering counterclockwise in directions. the clockwise Therefore, there arepuzzle only in two the ways minimum to number solveeither of the a clockwise moves: or move counterclockwise the directionthe knights until diagonally each opposite along corner of the for the the edges knights firstrequires reaches in time. a Either total of of these 16 symmetric moves. options expanding a partially constructed solution until a complete solution is reached. obtained will be ( Algorithmic Puzzles 16 hsbads htn w ig r lcdo daetvrial,horizontally, adjacent—vertically, on placed are kings diagonally—squares. two or no that so chessboard qae,wihipista h oa ubro oajcn ig nteboard the on kings nonadjacent of number 16. in exceed total cannot shown these the of as that each in squares, implies king one four-by-four which than more squares, 16 place to into impossible is board it Obviously, the 1.8b. Figure partition we board, the board on the on kings 16 of total the with up end column, third we 1.8a). the until (Figure in on, kings so four and place fourth, can we the one column, skip to first adjacent the board. is in squares the kings its placed of of the each column of because first column next the the in skipping after (four) Then, kings nonadjacent of number maximum mosblt fpaigmr hn1 o-takn kings. non-attacking 16 than more placing of impossibility tef ahr oedfcl aki opoeta tide ilsa optimal an yields Kings indeed Non-Attacking it that prove algorithm to greedy example. an is a provides puzzle design task greedy following to difficult The a solution. difficult more by not a solved is rather, be it a itself; cases can such these in that in solvable puzzles Usually be are algorithm. to there “tricky” Still, too fashion. usually straightforward are puzzles good approach: greedy optimal (globally) a cases some yield others. in in works the will fails approach and in simple-minded choices made This optimal problem. is entire locally step the to each of solution to at sequence available is a alternative choice best that constraints. the strategy—the hope problem’s of this the grab of “greedy” violating a without point Such gain central immediate the largest the is produce this step—and each At IUE1.8 FIGURE nodrt hwta ti mosbet lc oeta 6nndaetkings nonadjacent 16 than more place to impossible is it that show to order In the placing by start can we strategy, greedy the of prescription the Following n hudntepc ihbut rmahn o uze ovbeb the by solvable puzzles for hunt a from bounty rich a expect not should One a lcmn f1 o-takn ig.()Priino h or proving board the of Partition (b) kings. non-attacking 16 of Placement (a) (a) lc h raetpsil ubro ig nan on kings of number possible greatest the Place (b) 8 × 8 17 Tutorials 1,2,5,101,2,5,10 puzzle (#34) n i m 0 the fastest possible 1 2,52,5 1,101,10 + 9 not n puzzle. i 0 m 1 Coins On a Star 1 11 2,52,5 1,1, + 8 n i m 0 2 5 1 1,51,5 + 19 minutes, but this is 3 = Bridge Crossing at Night n 10 i m + 1 2 1 + A group of four people, who have one flashlight, need to 5,105,10 1) 2 + (5 + n i m 1) 1,21,2 2 5,105,10 + Greedy solution to the It would be instructive for the reader to revisit the The greedy algorithm, illustrated in Figure 1.9, would start by sending to the As our second example, we consider a puzzle that has become especially 1,2,5,101,2,5,10 solution (see this puzzle again later in the book (#7)). and solve it by the greedy approach without benefits of the graph’s unfolding. other side the two fastest people,and that then is, persons return A the and flashlight(1 B with (it more will the take minute). fastest 2 of Then minutes) available, the it that two, is, will that persons send is, Afastest and with to C person person the (5 A A other minutes) (1 and sideriver return minute). together the the (10 Finally, flashlight minutes). two the with The fastest total the tworequires amount persons is of persons (2 time remaining this greedy-based will schedule cross the popular since itMicrosoft. was reported to have been asked during job interviews at Iterative Improvement While a greedyimprovement algorithm algorithm constructs starts a withsolution some and solution improves easily piece upon obtainable it byvalidate approximation by such repeated an to piece, applications algorithm, a one of an needs somedoes to iterative simple stop make step. sure after that a To the finite algorithm numberindeed in of question solves steps and the that problem. the Consider final approximation the obtained following puzzle, which is a politically FIGURE 1.9 Bridge Crossing at Night cross a rickety bridge at night. A maximumtime, of and two any people party can that cross the crosses bridgewith (either at them. one The one or flashlight must two be people) walked must backA and have forth; takes the it flashlight cannot 1 be minute thrown. Person tominutes, cross and the person D bridge, takes person 10 minutes. B Aslower takes pair person’s must 2 pace. walk Find minutes, together the at person fastest the C way rate of they takes the can 5 accomplish this task. Algorithmic Puzzles 18 nta addt,cnie ntr h oain n lc rmi nsm re,say, order, some in it So from block possible. one locations location the best turn their in the with consider points candidate, Starting not initial algorithm: lowest is improvement iterative it and following that the highest on noticed the decided somebody they between then vertically But point E. and middle A the points rightmost and and B leftmost and the between A horizontally point middle the is which h itneb h oa ubro lcshrznal n etclyfo their measure vertically—from they and that stand. blocks—horizontally the Assume of to number homes homes? total place C, their the they B, by to should A, distance intersection distance letters the street the which by minimize At denoted to 1.10a. locations Figure stand the in their map at the live on They E and stand. D, lemonade a up set to Placement Stand Lemonade book remarkable his in Gardner Martin by aha!Insight discussed problem a of version correct FIGURE tp.()Dsacscmue ytealgorithm. the by computed Distances (c) steps. T o A E D C B t ntal,tefinsdcddt oaetersada nescin1(iue1.10b), (Figure 1 intersection at stand their locate to decided friends the Initially, a A l D 1.10 2 3 1 4 4 2 1 + + + + + 3 3 1 2 0 3 Gr8 p 131–132]. pp. [Gar78, a ntneo the of Instance (a) C 2 3 1 4 4 2 1 + + + + + 6 (a) 4 2 3 2 1 T o E D C B A t a 4 1 2 5 3 l 2 1 + + + + + 4 1 E 3 2 3 0 iefinsAe,Bed,Cty a,adEarl—want and Dan, Cathy, Brenda, friends—Alex, Five 3 2 0 3 5 2 3 + + + + + 2 eoaeSadPlacement Stand Lemonade 3 1 2 3 0 1 2 3 1 4 4 2 B + + + + + 2 3 2 0 1 4 1 2 (c) 2 T o E D C B A t a A 3 2 0 5 3 l 2 3 + + + + + 2 1 1 0 2 5 2 D 1 1 2 6 4 1 2 + + + + + 3 2 uze b h algorithm’s The (b) puzzle. C 2 1 4 1 0 3 3 5 1 2 4 2 2 + + + + + 3 (b) 1 4 2 1 0 2 1 2 3 1 4 4 2 2 + + + + + 3 E 1 1 0 2 5 2 5 3 0 2 3 2 B + + + + + 1 1 4 1 0 2 3 19 Tutorials global . . Finding an appropriate monovariant table of real numbers, is there an algorithm to make elements can be in no more than two states). There- n monovariant × mn m Given an puzzle (#74)—the general instance of this puzzle first problem and increasing in the second). after a finite number of steps. Site Selection In both examples considered above, we took advantage of some quantity with Is that all? Not quite. We also need to show that the algorithm’s operation It would be natural to try finding an algorithm that increases the number of lines Here is another example of a puzzle that can be solved by iterative improvement. While the final location marked by number 3 in Figure 1.10b certainly looks • It could attain only a finite number of values,• which guaranteed a stop When it reached its final value, the problem was solved. • It could change its value only in a desired direction (decreasing in the the following characteristics: fore, the number of all elementsequence sums of is tables also with finite. increasing Since sums, the it must algorithm stop generates after a a finite number of steps. cannot continue indefinitely without stopping.repeated applications of This the algorithm’s is operation can indeed create only the adifferent finite tables number case, (each of of because the (rows and columns) with nonnegativechanging sums the on signs each in of ain its row some iterations. column (column) (row) However, with negative! aattention A negative to neat the sum way total may sum to of overcome make thethe this the numbers total difficulty in sums of the is table. either to Since all pay ita the can line be row computed with sums as a or negative all sumtable. the definitely Therefore, column increases we the sums, can total changing simply sum the repeatedly of searchwe signs the for find in numbers a such in line a the with line, a we negative changeline, sum. the we If have signs achieved of our all goal its and numbers; can if stop. we do not find such a can be a tricky task. This has made puzzles involving monovariants a popular Such a quantity is called a Positive Changes optimality. In other words, howone do we block know away that from not itother only intersection? the are four inferior Well, intersections we choices need butlocation not is worry also indeed about the that our best, young it and entrepreneurs: the willthe this reader be will have true a for chance to any see this by solving up (north), right (east), down (south),is and closer left to (west). their As homes, replace soon the as oldthe a location same new with verification the location operation; new if candidate none and of repeat out the four to neighboring intersections be turns better,The consider algorithm’s the operation is current shown location ingiven optimal Figure in 1.10b, and Figure with 1.10c. stop the computed the distances algorithm. like a good choice, the algorithm does not provide a proof of the location’s all the row sums andnumbers in column any sums row or nonnegative column by as the changing only operation the allowed signs for the of algorithm? all the Algorithmic Puzzles 20 trigwt o n oiglf orgtaogec o,o ounb column by column or row, each column. along each right along to down left moving moving and 1 row with starting nescinBi iywt efcl oiotlsresadvria vne shown avenues vertical and streets 1.11a. horizontal Figure perfectly in with city a in B intersection Counting Path Shortest to solutions optimal from subproblems. efficiently substructure its constructed optimal be can so-called solution a optimal have its that must be so problem to the problem technique, the optimization this an to by For solved solution processes. decision a method multistage general which optimizing a as for a 1950s from the by in table invented Bellman, was Richard mathematician, a programming U.S. Dynamic prominent in obtained. be results then can the problem subproblems original recording smaller the and of once each solving only suggests it again, overlapping and solving again than subproblems Rather subproblems. overlapping with problems solving programming Dynamic Programming Dynamic involving puzzles other few book. a this of find section puzzle can harder reader the in most interested monovariants The the approach. of the this as Some such on toys. science, computer mathematical in just algorithms important as iterative dismiss monovariants to however, and Mathematical wrong, be given All-Russian improvement would It first example 77]. the p. [Win04, second for 1961 in problems the Olympiad practice example, among used For was competitions. above mathematical in topic sn hs omls ecncmuetevle of values the compute can we formulas, these Using fstreet of u oain n h ubro hretptsfo oteitreto fstreet of intersection the to A from i paths shortest of number the and notation) our where hretptsfo oteitreto fstreet of intersection the to A vertical from paths shortest and streets A street from of the paths intersection shortest the along of to number the right Therefore, avenues. going the down segments going segments horizontal of composed is n avenue and Let sa xml,cnie rbe fcutn hretpaths. shortest counting of problem a consider example, an As P P P [ i [ [ , 1 i i , j , ] (1 j j etenme fsots ah rmitreto oteintersection the to A intersection from paths shortest of number the be ]= j ]= − ≤ 1( P o vr 1 every for 1 i [ i P ≤ − [ i , )adavenue and 4) idtenme ftesots ah rmitreto to A intersection from paths shortest the of number the Find 1 sitrrtdb optrsinit satcnqefor technique a as scientists computer by interpreted is j , − j ]+ i 1 n avenue and ] nornotation): our in P ≤ [ i j , ≤ j − 5, 1 j j ] a efuda h u ftenme of number the of sum the as found be can P (1 o vr 1 every for [ i , ≤ 1 ]= j i ≤ − o vr 1 every for 1 5) n avenue and 1 < . ipe method simplex P i n hretpt here path shortest Any [ ≤ i , j 4 ] , ihrrwb row by row either 1 ≤ < j ( i j P ≤ ≤ [ r based are , i 4 − 5 . 1 , j ] in 21 Tutorials B B 5 5 5 5 1 3 1 ] 0 j 0 4 4 1 1 2 ] 1,1, j − , i i j [ [ P P 0 3 6 3 1 (a)(a) 1 (b)(b) 1 − 1]1] j 2 4 3 2 1 − j , i [ P 1 1 1 1 1 A A 1 i − (a) Dynamic programming way to computing the number of shortest paths 4 3 2 1 i ) intersection. (b) Numbers of the shortest paths from intersection A to each j , 1.11 i to the ( FIGURE street-avenue intersection. Algorithmic Puzzles 22 eomne ssml plctoso hsstrategy. this of applications simple as recommended forward, banda h ubro ast hoetreoto ee ifrn hns that things, be different can seven paths of out shortest three as the choose out to is, of ways segments number of vertical number total three the the the as obtained Hence, of choice possibilities. the seven in the segments; other of vertical each three from and differ segments horizontal paths four the of up made is path shortest ecmue ln otws onrhatdaoastruhteitretos triga on A. point at called starting structure combinatorial intersections, famous the the of through elements diagonals are values northeast These to southwest along computed be eto 5.4]). Section o lotalagrtmcpolm,sc on rw ihtepolmsize. problem the with grows count a such out Figuring problems, algorithmic executed. is all step basic almost algorithm’s the For times of number the counting by done is in This listed are which [Cor09], be and can [Kle05], treatment difficulty. in-depth of [Lev06], order more as increasing a such level; accessible textbooks most the in the review found on We to this puzzles. do is few to a tutorial on them try short them will of this illustrating analysis, some of algorithm design, goal for techniques The algorithm standard analysis. with algorithm deal an book require this do in puzzles most Although TECHNIQUES ANALYSIS upsdy tto aljs e iue ocm ihtease ygrouping by answer them. 5 the among with come be to to minutes few happened a genius could just teacher mathematical Carl The took a it while. that Supposedly, a quite course, for of students know, his not occupy to hope the in probably integers positive 100 first the of sum the compute old, to years class 10 the about asked was teacher Gauss his When history. in (1777–1855), mathematicians greatest Gauss the Friedrich of Carl one about story apocryphal well-known a is There algorithms of efficiency and formulas summation few A onigptsi esrglrgis oseti,terae a att ov the solve to want for may case reader the the this, not see often Paths To Blocked grids. is regular it less example, in simple paths counting this for programming dynamic than ahmtclfrua htg upiigyfri nlzn algorithms. analyzing in far surprisingly important go some that reviewing formulas by mathematical start us let So mathematics. involves surprisingly, not h edrfmla iheeetr obntrc ilnt httevle of values the that note will combinatorics elementary with familiar reader The h rbe a lob ovdb ipecmiaoilagmn.Every argument. combinatorial simple a by solved be also can problem The nagrtmaayi sal ek oacranteagrtmstm efficiency. time algorithm’s the ascertain to seeks usually analysis algorithm An hl oeapiain fdnmcpormigaeayhn u straight- but anything are programming dynamic of applications some While C (7 aiu u Descent Sum Maximum , 3) o fast how uze(1)i h ansection. main the in (#13) puzzle = 7 ! / (3 tgosi h anga fteagrtmaayi.Counting, analysis. algorithm the of goal main the is grows it ! 4 ! ) = 1 + 35 2 . 5 #0 and (#20) +···+ u hl h obntra ouini faster is solution combinatorial the while But 99 ikn pCoins Up Picking + 100 , aclsTriangle Pascal’s #2 a lobe also can (#62) P [ eg,[Ros07, (e.g., i , j ] a also can 23 Tutorials (1) (2) ) n . 2 puzzle (#9), , 5050 1) = + +···+ 50 . n 4 · n ( positive even numbers, . n + 1 1) n . 2 = 101 (2 − + 1 ) 1 n = n − − ( + ) Mental Arithmetic n n 2 64 = 51) 2 2 n = + + = n + +···+ 2 1) 63 2 (50 1) 2 positive integers yields the formula . − 2 n + n − n n (2 = ( 2(1 +···+ 2 1) +···+ = +···+ 2 n + 2 1) 2 + positive odd numbers, we get n 99) + ( 2 +···+ n +···+ − n + 1 4 n 2 + − (2 1 + (2 + 3 1) 1 +···+ + 4 + + Presumably, the game of chess was invented many centuries ago in 2 2 n + 100) 2 + +···+ (2 n + 3 2 (1 (1 + = = 1 Formula (1) is almost indispensable in algorithm analysis. It also leads to several Now we are ready to consider our first example dealing with an algorithm Well, according to formula (2), the total number of grains Shashi requested is Another very important formula is the sum of consecutive powers of 2, which other useful formulas. For example, for the sum of the first As an exercise, we recommendwhich exploits to this the formula and reader its the derivation. analysis. equal to we already used in the first tutorial: If it took him just 1 secondhave to needed count to count each all grain, the the grains comes total to amount about of 585 time billion years, he over would 100 times Chess Invention northwestern India by a sage namedking, Shashi. the When king Shashi liked took the hiswanted. game invention Shashi so asked to for much his some that grain to hewheat be offered was obtained the as to follows: inventor be just any placed a single rewardfour on grain on he the of the first third, square eight of on theWas the it fourth, chess a and board, reasonable so two request on, on on until the all the inventor’s 64 second, part? squares had been filled. and for the sum of the first Generalizing this to the sum of the first the numbers into 50 pairs with the same sum of 101: we obtain Algorithmic Puzzles 24 al noti category. this into falls on ra prxmt oml niaigisrt fgot.A neape we example, an 88]. p. As [Gar99, growth. the question of for puzzle-like following rate formula the its compact consider indicating exact formula an approximate either an the finding or Then of executed. count goal is the step principal with its simplified times is of analyzed number sum the be for can sum algorithm a up nonrecursive setting a by an Typically, with instance reached. trivial is a itself until solution applying problem obvious by same the work of not instances does smaller it and that smaller to means This recursive. not is that algorithm shrink solved be to remains the repeatedly that for problem algorithm by The the fast. of very work to size growth the of and making rate exponential by strategies) the advantage turns our This design half. say, algorithm by, size the problem the reducing on tutorial strategy decrease-by-a-constant-factor the the on (see are based efficient usually more are Still algorithms These size. input’s their to proportional ubro ai tp o hsagrtmi ipyeuvln ocutn h total the counting to After equivalent squares. simply unit is of algorithm number this for steps basic of number qae rm1t 2 to 1 from squares nlsso orcriealgorithm nonrecursive a of Analysis algorithm. The an of reward. time running modest the his for acceptable count more to much clearly minutes less is needed growth 14 have and would he hour second, 1 per grain than one counting of speed same the With of demonstration good a is This of Earth. rate planet monstrous the the of age estimated the than more trtosad e qae l rudteotie o ayui qae ilbe will squares unit many the How outside. after the there around all squares new adds iterations Build-Up Square a that fact the by surprised be not will reader The iue1.12. Figure (2 ahsur ftecesor,Sah se o digtogan?Te h total to the equal Then been grains? have two would adding grains for of amount asked Shashi chessboard, the of square each small very but all problem. for the impractical of are instances size problem the with exponentially grow that n h ai tpo hsagrtmi digaui qae hrfr,cutn the counting Therefore, square. unit a adding is algorithm this of step basic The vnfse r loihsta are that algorithms are faster Even htwudhv apndi nta fduln h ubro risfor grains of number the doubling of instead if happened have would What − )sc qae.Terw bv n eo twl oti d ubr of numbers odd contain will it below and above rows The squares. such 1) n hieain h eut o h rtfwieain r hw in shown are iterations few first the for results The iteration? th nagrtmsat ihasnl qaeado aho t next its of each on and square single a with starts algorithm An n − xoeta growth exponential 1 3 + . ic h u ftefirst the of sum the Since 3 +···+ n ubrGuessing Number trtos h ogs oiotlrwwl contain will row horizontal longest the iterations, (2 biul,agrtm htrqietime require that algorithms Obviously, . · linear 64 − hs loihsrqietime require algorithms These . aedsusdi h rttutorial first the in discussed game 1) n = − orcriealgorithm nonrecursive 64 d ubr seulto equal is numbers odd 1 2 . logarithmic quadratic algorithms. aeof rate san is 25 Tutorials 1)) 1 squares. 1 diagonals th iteration. − + n n n − ( 2 =3 n disks of different = 3 − . n n Counting Triangles 1 2 n 2 + +···+ n = 2 2 2 1) − + 1) − 2 n n − Therefore, the total number of 2 . 4(1 n (2 ( algorithm. 1) = . + + + 1 1 − 2 1) i + n 3)) = − n 2 − n 1) puzzle. n − (2 − 2 (2 n + n =2 2 unit squares that alternate with 2 = 2 4( Square Build-Up n n 1) = 2 ) is equal to 4( − / n +···+ n n 3 ≤ 2( 1) +···+ Tower of Hanoi i + 2 = − · < iterations can be computed as n 4 n 2(1 4( In the general instance of this puzzle, there are diagonals with + 1 unit squares for the total of + 1 n First iterations of the · 1 − the total number of unit squares will be equal to 4 n = , 2 1.12 + 1 1) th iteration (1 i − For another example, we suggest to the reader solving the While there is certainly nothing wrong with using standard techniques, it is =1 = 1 n n puzzle (#52). each with sizes and three pegs. Initially, alllargest the on disks the are bottom on the anddisks first the to peg smallest another in peg on order by top. of a sequence The size,and of it the objective moves. is is Only forbidden one to to disk place transfer can a all be larger moved disk the at on a top time, of a smaller one. It comprises always a good idea to trycan count exploiting the the squares specifics by the of diagonals the of the problem shape given. obtained after Here, the one Tower of Hanoi Analysis of a recursive algorithm We will illustrate the standardconsidering technique the classic for analysis of a recursive algorithm by One can also solve the puzzle bythe noting that the number of unit squares added on ( FIGURE unit squares after Algorithmic Puzzles 26 osletepzl with puzzle the solve to hsagrtm Let algorithm. this transfer To iue11) eoti h olwn qainfor equation following the obtain we 1.13), Figure FIGURE n oet ov h rbe o n ik ehv h olwn diinto addition following the just have we makes disk, algorithm one the relation: for say recurrence Since problem not the sequence. the does solve the it to of because move term uniquely, one first sequence the the about specify not anything the does that this says that it Note case, our In sequence, terms. the preceding of its to relates sequence a of called are equations Such as simplified be can this course, Of rmpg1t e 3. peg to 1 peg from uigpg1a uiir) fcus,if course, Of auxiliary). as 1 peg (using ik rmpg1t e wt e saxlay,te oetelretdisk largest the move then auxiliary), transfer finally, as and, 3 3, peg peg to (with 1 2 peg peg from directly to 1 peg from disks condition biul,mvn ikfo n e oaohri h ai prto of operation basic the is another to peg one from disk a moving Obviously, 1.13. Figure in illustrated is that solution recursive elegant an has problem The 1.13 osmaie ehv h olwn eurnerlto ihteinitial the with relation recurrence following the have we summarize, To . n eusv ouint the to solution Recursive > M ik rmpg1t e wt e saxlay,transfer auxiliary), as 2 peg (with 3 peg to 1 peg from disks 1 M ( n ( M ) n M = ) ( , n ( etenme fds oe aeb h algorithm the by made moves disk of number the be ) M slre y1ta wc t rcdn term preceding its twice than 1 by larger is M n n eurnerelations recurrence ) ( ik.Floigteagrtmsdsrpin(e also (see description algorithm’s the Following disks. (1) = n 1 − 2 = M 1) ( ,wih o upiigy scle the called is surprisingly, not which, 1, oe fHanoi of Tower n + − 1 n 1) + = 2 M + 1 eas hyseiyhwthe how specify they because , ( for 1 ipymv h igeds directly disk single the move simply n − n M puzzle. )for 1) − 3 ( n n ik rmpg2t e 3 peg to 2 peg from disks 1 ): > 1 . n > 1 . M ( n n n hterm th hterm th − initial n − 1) 1 . 27 Tutorials . 1 − n . 2 1 = − ) n n 2 ( = M ) by the formulas n 1 ( + M , , 1 1 1) − > > puzzle (#83), one of many 1 n n − n 2(2 1 for 2 for ) = n + + ) suggests the formula ( 1 n ( + 1) 1) M − − 1) nM 11 37 23 415 The easiest way to prove that it is valid for all n n . This is not due to the fact that this particular − ( ( n . n 1 . . M M ( 2 1 3 2 M = = = = = 1 Restricted Tower of Hanoi ) ) n n − ( (1) (1) ( disks: 1 M M M M n 2 ’s. This is indeed the case because 1 and 2 years, which more than one thousand times longer than the n = − 13 n 10 2 (1) · = M ) ’s. n n ( M 1 is to substitute the formula into the equation to see whether we get the The inspection of the first values of Rather than using one of the standard methods for solving such equations, which As as exercise, the reader may want to solve the recurrence for the minimum > n variations of the classic version: can be found in the textbooksus mentioned try in the inductive the approach: first compute the paragraph first of few this values of tutorial, let above, try to identify a general pattern, andpositive then prove that the pattern holds for all number of moves in the estimated age of the universe. Thus, we have an exponential algorithm,time which even will for run moderate for values an of unimaginablyalgorithm long is poor; in fact,algorithm it is possible not for difficult to thismakes prove problem. that it It this so is is computationally the theversion most hard. efficient problem’s of This the intrinsic might Tower difficulty be ofmathematician that a Hanoi Édouard puzzle, good Lucas, as news: in publishedhave in the been by the moved 1880s, its by original the monks inventor, from world themonks a mystical do French will Tower not end of eat, Brahma. sleep, after Assuming orafter that 64 die the about and disks move 3 one disk per minute, the world will end Obviously, condition for the number of moves madeof by Hanoi the puzzle recursive with algorithm for the Tower equality for all such Algorithmic Puzzles 28 Fgr 1.14b)? (Figure uzeaotwlsi h l rsinct fKönigsberg. of city Prussian old the in walks about puzzle puzzles. Journey ast xli h nain da Puzzles idea. invariant the exploit to ways board the on squares two. light by differ and corners dark opposite entire diagonally of the two numbers of without tiling the desired because a same impossible Hence, the board. is covers the board of tiling squares domino light any and square, dark of light number one one and since different: dark is one here covers invariant The domino even. obviously is board a such odd. on is squares question in board the on squares squares covered of number of the number while the here), of invariant parity the even is (this even always is squares covered ihdmne an dominoes with 8 Chessboards Deficient of Tiling Domino our For invariant. an of idea the an of purposes, discussion brief a with tutorial this conclude We Invariants FIGURE ignlyopst squares. opposite diagonally h uzebtfisfrterqie nlsae e scnie e examples. few a consider us Let state. final required of the state for initial fails the but for the puzzle holds that the property show invariant the to because used solution often no is has invariant problem an questions, puzzle-like For problem. the × h motneo nivrati ifrn etn a ese ntefamous the in seen be can setting different a in invariant an of importance The ngnrl h vnodprt n ooigaetoo h otwdl used widely most the of two are coloring and parity even-odd the general, In the of number the though even “no” also is question second the to answer of The number the tiling, domino any in “no”: is question first the to answer The 8 hsbadmsigoecre qae(iue11a?b si osbet tile to possible it Is b. 1.14a)? (Figure square corner one missing chessboard 1.14 #8 r eomne oterae stpclrpeettvso such of representatives typical as reader the to recommended are (#18) a hsbadmsigoecre qae b hsbadmsigtwo missing Chessboard (b) square. corner one missing Chessboard (a) invariant (a) 8 × 8 sapoet hti rsre yayagrtmta solves that algorithm any by preserved is that property a is hsbadmsigtodaoal poiecre squares corner opposite diagonally two missing chessboard .I tpsil otl ihdmne an dominoes with tile to possible it Is a. atBall Last #0 and (#50) (b) Corner-to-Corner A 29 Tutorials : c a d Euler circuit b . has no solution because it fails this c Was it possible, in a single stroll, to cross all seven is even for every vertex. This invariant property since there is more than one edge connecting some of The Königsberg Bridges Problem d a degree— multigraph The Königsberg Bridges Problem Multigraph of Diagram of Königsberg’s seven bridges over the river connecting the b 1.16 1.15 The question then is whether the multigraph in Figure 1.16 has an The puzzle was solved by the great Swiss-born mathematician Leonhard Euler a sequence of adjacentreturning vertices to that the starting traverses vertex. all Eulerenter noticed the a that vertex edges exactly any the such exactly same circuit number oncea would of times before have circuit as to it can leaves only the vertex. exista Hence, such in vertex—called a its multigraph in which the number of edges touching implies that (1707–1783). First, Euler realized that walkingriver along or a an land island—is mass—a irrelevant bank toconnections the of problem. provided the The by only the pertinent bridges. informationto is In transform modern the terms, problem this to insight(Actually, the enabled it question is him about a the graph shown in Figure 1.16. its vertices.) mainland and two islands. FIGURE FIGURE The Königsberg Bridges Problem bridges of Königsberg exactly once andriver return with to its the two starting islands point? and A seven sketch bridges of is the shown in Figure 1.15. necessary condition: every vertexdegree. of Moreover, the the multigraph same in analysis Figure implies that 1.16 there has was an no odd walk crossing all Algorithmic Puzzles 30 aeamv.Tepa otne ytrsutlbt hcesaecpue.Acapture A each captured. (h) are hen chickens both the until and turns (r) by continues rooster play the The then move. left a (M) and make square, man and one the right move 1.17a, or each Figure (W) in down a woman indicated and and and positions the up person with directly a Starting move, square, diagonally. not each neighboring but On a hen. to a move counters and can two rooster chicken and a wife representing his and color farmer another a of representing color one of counters two with euneof sequence ie ntenx w etne.Sneol n a ic a eboe tatime, Hence, a at 1. broken by solution be pieces can the of piece number reading bar the before one increases only break it Since any solve sentences. two to next try the and in given stop should reader the scientists, iiu ubro a rasi a a eboe nyi tagtln n only and time. line a straight a at in broken only be broken can be bar can one bar a if breaks bar of number minimum n cue odo taighspzlsadpbihn hmudrhsonname. own his under them publishing and puzzles his stealing of Loyd accused and raigaCooaeBar Chocolate a Breaking can path the Euler solve an to another analysis not by this proved circuit of Tracing formally advantage Euler later take and may an himself vertices. reader Euler neither its The by mathematician. case, of noted was pair the fact multigraph. every not This connected between is exist.) a path it in a if is path course, there Euler Of if an connected and is circuit multigraph Euler (A an of existence for walk the which in vertices two end. and exactly start except to degree have would even an have to have would starting the an to called returning walk, a of such requirement For point. the without even once exactly bridges the 6 Corn the in Chickens solution. a of nonexistence the implying applications. practical and education, usefulness science, potential of serious and example for an computing puzzles as of to to pointed applications often also important is It with research. operations mathematics of branch a theory, raoso uze nhsoy er .Ddny[u0,p 5,adSmLoyd Sam and 95], p. [Dud02, Dudeney 8]. renowned E. p. most [Loy59, Henry two history: the in wording—by puzzles and of size creators board the published— puzzle in a variations is Here trivial proceed. with must algorithm an way a out pointing by role ogtfo single a from get to uee n odhdclaoae o oeyasutlDdnyboeoftecorrespondence the off broke Dudeney until years some for collaborated had Loyd and Dudeney Today, oapeit hspzl,wl-nw mn ahmtcasadcomputer and mathematicians among well-known puzzle, this appreciate To ytewy hs odtostr u ob o nyncsaybtas sufficient also but necessary only not be to out turn conditions these way, the By h etpzl rvdsa xml hr nivratpasarl te than other role a plays invariant an where example an provides puzzle next The ial,w osdra xml hr nivratpasamr constructive more a plays invariant an where example an consider we Finally, uze(2)i h ansection. main the in (#28) puzzle h öisegBigsProblem Bridges Königsberg The nm 6 − loe breaks. allowed 1 n h aei lydo a on played is game The × m ra an Break ic to piece ue path Euler n nm × m oeit l h etcso h multigraph the of vertices the all exist, to , 1 hclt a into bar chocolate scniee pigor o graph for springboard a considered is × 5 ics hc sotie by obtained is which pieces, 1 × 8 or ersnigacornfield, a representing board nm − nm rasaeneeded are breaks 1 qae ihthe with squares Figure any 31 Tutorials h W (b)(b) M puzzle. (b) The board colored as a r h Chickens in the Corn W (a)(a) (a) Board of the M 1.17 This concludes the tutorials. As to the question of which of the strategies needs Still, the strategies and techniques discussed above provide a powerful set of Of course, even if one knows which strategy needs to be applied, it might still be It does not take much effort to realize that the man cannot capture the rooster r to be applied towould a have particular lost puzzle, their attraction thereare as is just an general no intellectual tools, answer! entertainment.) whichpuzzle. The (If may With strategies there a and lot may was, of practice, not puzzles onea work can particular successfully hope tool to for might develop a some work intuition particular successfully,to about but be when foolproof. such intuition is certainly not going tools for solving problems ofthan an those that algorithmic mathematicians nature. have They atas their are Pólya’s disposal, also “How despite to more such Solve specific famous It” efforts [Pol57]. far from a simple task. For example, proving thatdone a by puzzle using has no an solution invariant. is But typically findingmight a be specific difficult, invariant even for if a one particular knows problem lead that, to say, a using solution. parity Again, or with board practice coloring the might task gets easier but not necessarily easy. and that the woman cannot capture the hen.a Indeed, a person capture and can a only occur bird when occupy twocolors adjacent if squares, the which are board’s always squares of areBut the colored opposite the as man those of and aremains the chessboard valid rooster (Figure after start 1.17b). both at makesame the observation one same-color is and squares, true hence and for anyfor the this the finite woman property hen number and and of the the hen. woman moves.cooperate should Hence, in The go their the for capture, man one the of should rooster. them go Evenon can the if be ninth. taken the on chickens the do eighth not move, the other chessboard. FIGURE occurs when the farmer or his wifeThe can objective pounce is on a to square accomplish occupied this by task the in chicken. the minimum number of moves. 2Puzzles

EASIER PUZZLES

1. A Wolf, a Goat, and a Cabbage A man finds himself on a riverbank with a wolf, a goat, and a head of cabbage. He needs to transport all three to the other side of the river in his boat. However, the boat has room for only the man himself and one other item (either the wolf, the goat, or the cabbage). In his absence, the wolf would eat the goat, and the goat would eat the cabbage. Show how the man can get all these “passengers” to the other side. 2. Glove Selection There are 20 gloves in a drawer: 5 pairs of black gloves, 3 pairs of brown, and 2 pairs of gray. You select the gloves in the dark and can check them only after a selection has been made. What is the smallest number of gloves you need to select to guarantee getting the following? (a) At least one matching pair (b) At least one matching pair of each color 3. Rectangle Dissection Find all values of n > 1 for which one can dissect a rectangle into n right triangles, and outline an algorithm for doing such a dissection. 4. Ferrying Soldiers A detachment of 25 soldiers must cross a wide and deep river with no bridge in sight. They notice two 12-year-old boys playing in a rowboat by

32 33 Puzzles 1 9 1313 1515 puzzle. 5 3 7 1111 2 6 1010 1414 8 4 1212 1616 Row and Column Exchanges 8 4 1212 1616 3 7 1111 1515 2 6 1010 1414 Initial and target tables in the 9 5 1 1313 Row and Column Exchanges Can one transform theexchanging its left rows and table columns? in Figure 2.1 into the right table by the shore. The boat is soone tiny, soldier. however, How that can it the canin soldiers only joint get hold possession two across of boys the the or river boat?shore and How to many leave shore times in the does your boys algorithm? the boat pass from Bridge Crossing at Night Four people need to cross a ricketyside. footbridge; It they is all begin dark, on and thecan same they cross the have bridge one at flashlight. one time.people, A Any must maximum party have that of the flashlight crosses, two with either people them. oneback The or and flashlight two forth; must it be cannot walked be thrown,to for cross example. the Person 1 bridge, takes person 1and minute 2 person 4 takes takes 2 10 minutes. minutes, A personslower pair person’s must 3 pace. walk takes For together example, at 5 if the minutes, person rateit 1 of will and the take person them 4 10 walk minutes together, toflashlight, get to a the total other of side. If 20 person minutes17 4 have minutes? returns the passed. Can they cross the bridge in Assembly A jigsaw puzzle contains 500 pieces. A “section”or of more the puzzle pieces is that a have set been of connected one to each other. A “move” consists Predicting a Finger Count A little girl countsfollows. from She 1 starts by to calling her 1000 thumb 1,ring using the finger first 4, the finger and 2, fingers little middle finger of finger 5. Then 3, finger her she 6, reverses left middle direction, calling finger hand the 7, ring the as first fingercalls 8, her and first her finger thumb 10, 9, and after so whichon on. she which If finger she continues will to she count stop? in this manner, 5. 8. 7. 6. FIGURE 2.1 Algorithmic Puzzles 34 IUE2.2 FIGURE 13. 12. 11. 10. 9. iue23 opt a rs h ecdofae hw nge nthe in grey in shown area off fenced in the shown cross as in can figure. avenues B path vertical point No and to 2.3. streets A Figure horizontal point perfectly from with paths city shortest a different of number the Find Paths Blocked nFgr ..Cluaetettlsmo h al’ ubr nyu head. your in numbers table’s the of sum total the Calculate 2.2. Figure in si osbet iea 8 an tile to possible it Is Tiling Questionable coins? needed fake weighings the with of stack number the minimum identify the to of is weight What exact coins. the 11 of are determine number weighs can stacks any that fake scale other every analytical the and an have grams, in You 10 coins grams. weighs the one coin all in genuine coins and Every the counterfeit, genuine. of are All stacks coins. these identical-looking 10 of of stacks 10 are There two-pan Coins a Fake of Stack with A coin fake the minimum weights? identify without the to scale is balance What needed coins. weighings genuine the of counterfeit than number lighter is be coins to these known of is one and coins; identical-looking eight are There Coins Eight Among Fake A A10 in Arithmetic Mental moves of number completed? minimum be the can puzzle is the which What sections. two connecting of w oiosfr 2 a form dominoes two × al fnmest esme pi the in up summed be to numbers of Table 0tbei le ihrpaignmeso t ignl sshown as diagonals its on numbers repeating with filled is table 10 10 9 3 2 1 . . . 10 11 3 9 2 11 10 9 3 × × 11 10 square? 2 or ihdmne (2 dominoes with board 8 9 11 10 9 ... 11 10 ... 9 10 11 9 etlArithmetic Mental 10 17 11 9 10 11 18 17 9 × 11 10 19 18 17 ie)s htno that so tiles) 1 . . . puzzle. 35 Puzzles 0 all the > n 8 chessboard can × B 8 chessboard are mistakenly colored in blocks of two × A 8 board to be reassembled into the standard chessboard. n n n 5 × 3 6 × × × n n n An 8 Grid of city streets with a fenced off area (shown in gray). (c) 6 be reassembled from the pieces obtained.of What pieces is into the which minimum the number reassembled? board needs to be cut and how should they be colors as shown in Figure 2.4. Youseparating need its to rows cut and this columns board so that along the some standard lines 8 boards of the following dimensions can be tiled by right trominoes: (a) 3 (b) 5 Tromino Tilings For each of the three cases, prove or disprove that for every Chessboard Reassembly The squares of an 8 15. 14. FIGURE 2.4 FIGURE 2.3 Algorithmic Puzzles 36 IUE2.5 FIGURE 20. 19. 16. 18. 7 A 17. fcus)t n h ags u nadsetfo t pxt h base the to apex level. its each from per number descent one a numbers, adjacent in of sum sequence a largest through in the shown find search, one to exhaustive an the course) than of like efficient (more triangle algorithm a an Design in 2.5. Figure arranged are integers positive Some Descent Sum Maximum total there are the pages If many how 1. book? 1578, the to with in equal starting is used sequentially digits decimal numbered of are number book a of Pages Numbering Page L-shaped are the moves in square knight’s direction.) one perpendicular by (The followed vertically corner? or horizontally right squares two upper jumps: the at end and o aet make to have You all cover Pancakes tiling, should Making they overlaps. a no but with In exactly ways, board strategies). the different of squares design in the oriented algorithm be adjacent on can three tutorial trominoes by formed the tiles (see L-shaped squares are trominoes right that Recall steeawyfraceskih osata h oe etcre fa of corner left lower the at start to knight chess a 8 for standard way a there Is Journey moves. Corner-to-Corner diagonal no A makes king the if question same the Answer (b) a h igi hs a oet n egbrn qaehorizontally, square neighboring any to move can chess in king The (a) a as time of amount in minimum job the of this is function two do What or to time. algorithm one of frying an amount whether Design minimum sides; of time. the both same regardless the on minute, at 1 fried fried are takes be pancakes pancake to a has of pancake side Each one time. a at pancakes igsReach King’s fa nnt hsbad nhwmn ifrn qae a tb after be it can squares n different many how in chessboard, square infinite some an on of starts king the that Assuming diagonally. or vertically, rageo ubr ihtemxmmsmpt hw ytecircles. the by shown path maximum-sum the with numbers of Triangle moves? × n ? hsbad ii l h qae ftebadeatyonce, exactly board the of squares the all visit chessboard, 8 n 1 ≥ 3 acksuigasiltta a odol two only hold can that skillet a using pancakes 1 6 5 4 2 4 9 7 6 37 Puzzles smaller squares n wants to find out the time 1) so that no two pieces in > n chessboard ( n 1 checkers on the table, some of them are red × > n n for which one can dissect a square into n The History of the World Science teams played each other once. Assuming there were no ties, is it n horizontally and one square vertically,one or square two horizontally from squares the vertically square it and occupies.) diagonal.) vertically, or diagonally.) same column.) (c) The king. (The king threatens any square adjacent to it horizontally, question placed on two squares of the same color can(a) threaten each other: The knight. (The knight threatens any square that is two(b) squares The bishop. (The bishop threatens any square that is on the same (d) The rook. (The rook threatens any square in the same rowThe or squares in threatened the by each of these pieces are shownThe in Best Figure Time 2.6. to Be Alive An editor of when the largest number of prominent scientists were alive. Thescientists prominent are, by definition, thedates people of mentioned their in birth thebook.) and book death. Devise with (No the an living algorithmits scientists for input. are The this included entries in task inpersons’ the the if birth index and it are death has sorted years.was alphabetically the If born, and assume person book’s that give A the index former the died event the as happened before same the yearFind latter the one. person Rank B If we generate a listin lexicographic of order all starting “words” with GINRTU madewhat and of ending position with letters UTRNIG, in G, I, the N, list R, will T, be and occupied U by TURING? (Alan Turing and outline an algorithm for doing such a dissection. Team Ordering Suppose you have the results ofwhich a completed round-robin tournament in always possible to list the teamsgame in with a the sequence team so listed that immediately every after team it? won the Polish National Flag Problem There is a row of Square Dissection Find all values of and some are white. (Red andflag.) white Design are an the colors algorithm ofcheckers to the precede rearrange Polish all national the the white checkers ones.examination so The of that a only checker’s all operations color allowed and the are theminimize red swapping the the of number two of checkers. swaps Try made to by your algorithm. Chessboard Colorings For each of the following chess pieces, findneeded the minimum to number of color colors an 25. 26. 22. 23. 24. 21. Algorithmic Puzzles 38 IUE2.6 FIGURE 28. 27. itn orpnofteppro on akoe n iei t rpoethat prove or it, so. in do line without to any impossible figure over is back the it going trace or either paper the 2.8, off Figure pen your in lifting figures three the of each For before a Tracing route? Figure once find a exactly such to find cities you was Can the point. game all starting the the through to returning pass of would object that The route connections 2.7). holes circular representing Figure with grooves (see board them and wooden between cities a on world played major was representing game The the as Game.” world the “Icosian to presented mathemati- and Irish (1805–1865) Hamilton renowned William the Sir by cian invented puzzle 19th-century a is This Game Icosian The science.) computer developing theoretical in role leading a played achievements, who, remarkable scientist other computer among and mathematician English an was (1912–1954) qae hetndb a ngt b ihp c ig d rook. (d) king, (c) bishop, (b) knight, (a) by threatened Squares (c) (a) (b) (d) 39 Puzzles (c)(c) the magic squares of all units long. n 3 table filled with nine distinct integers . (b)(b) × Icosian Game Three figures to trace. The graph of the (a)(a) from 1 to 9two so corner-to-corner that diagonals the is the sum same. of Find the numbers in each row, column, and order 3. Cutting a Stick A stick 100 units longminimum needs number to of be cuts cut required intopieces if at you 100 the are unit same allowed pieces. time? to Also Whatwith cut outline is the an several minimum the algorithm stick number that of performs cuts for this a task stick of The Three Pile Trick A magician asks areturn person it to back select without showing one the of card to 27 the cards magician. After in the a choice pack and then Magic Square Revisited A magic square of order 3 is a 3 30. 31. 29. FIGURE 2.8 FIGURE 2.7 Algorithmic Puzzles 40 33. 32. 34. 35. b idaltevle of values the all Find (b) h onwl aet ean ecncniu,sy ihtefollowing the with say, continue, can We 7 remain. moves: of to sequence have will coin the a o aean have You (a) Pseudo-Magic and Magic tournament? a such in winner? there a are get rounds to many needed How matches of number (b) total the is What a such (a) If determined. is winner single with starts a tournament Slam until play Grand the of from rounds tennis eliminated subsequent immediately the is as player losing tournament—such championships—every single-elimination a In that names Tournament he Single-Elimination layout, final the in trick. card the which selected Explain told card. the is he contains When piles time. last the the for of two piles the three between into pile cards the the the about deals places and informed he again, is card magician selected the the After containing pile before. the as deals piles shuffling, any three without the into and, cards selected piles with two pile who other the person the places then between The magician card The that turn. it. in contains pile pile which asked into each is up card to face cards card the one all deals piles, and three pack the shuffles magician the made, is rtci npit6adte oigi opit1(eoe 6 (denoted 1 point to it moving then and the 6 placing point by on start coin can first we example, For this again. in to moved positioned be line been cannot a has it coin manner, along a moved once then (ii) and and point, point unoccupied unoccupied needs another an coin on a first (i) placed restrictions: be following to the with another, be should after coins one The at 2.9. placed coins Figure of in depicted number star possible eight-pointed largest the the of place points to is puzzle this of object The Star a on Coins ie n8pn u ulo ae n w mt uso -ad3-pint and 5- of filling completely others. jugs by into jugs empty jugs the emptying of two and/or one up in and water of water pints 4 of exactly get full capacity, jug 8-pint an Given Jugs Three c o aymr ace edt epae odtrietesecond- the determine to played be to need matches more many How (c) etpae ae nteifrainpoue ytetournament? the by produced information the on based player best n ounsm utb h aebttedaoa usmybe may sums diagonal the but same the different. be must sums column and a is it in hog ,icuie n ubrprcl.Teojc st oti in this do to 3 is every object that way The a cell. such per number one inclusive, 9, through ausof values al ihitgr hog ,icuie ota vr 3 every that so inclusive, 9, through 1 integers with table suomgcsquare pseudo-magic n ≥ n o hc hscnb done. be can this which for 3 × → n n al hs el r ob le ihitgr 1 integers with filled be to are cells whose table lyr,dtrietefollowing: the determine players, ,8 2, n × → ≥ qaei ti ai qae idalthe all Find square. magic a is it in square 3 o hc ti osbet l an fill to possible is it which for 3 ,7 3, naped-ai qae l h row the all square, pseudo-magic a In . → 4,8 → ,wihpae v coins. five places which 5, → × ) where 1), square 3 n × n 41 Puzzles 8 ’s − × Z-tetrominoZ-tetromino ’s and 1 squares, + 3 × 2 table with n 1 T-tetrominoT-tetromino 4 × board so that no more than n n × n L-tetrominoL-tetromino counters on an n 5 8 for which one can fill an n place 2 Square tetrominoSquare tetromino , 1 > n 6 7 Five tetromino types. A star for placing coins at its points. -Counters Problem 2.10 n (c) 16 L-tetrominoes chessboard with the following? (a) 16 straight tetrominoes (b) 16 square tetrominoes which are shown in Figure 2.10. (one per cell) so that every cellsign. has exactly Two one cells neighbor are with considered the neighbors opposite ifor they the are same either column. in the same row 2 For any two counters are in the same row, column, or diagonal. Tetromino Tiling There are five types of tetrominoes—tiles made of four 1 Is it possible to tile (i.e., cover exactly without overlaps) an 8 Limited Diversity Find all values of 37. 38. 36. Straight tetrominoStraight tetromino FIGURE FIGURE 2.9 Algorithmic Puzzles 42 FIGURE FIGURE 41. 40. 39. wthcnb ipdbtentopstos hrb ogigteon/off the toggling thereby positions, two between flipped be can switch hr sacrl of circle a is There Lights of Circle The 3 a on knights four are There Knights Alternating Four rvrial daetsursadi o eurdt eunt t starting its to return horizontally to of required such not sequence is no square. any and that through squares prove adjacent proceed vertically or may passes or once path that exactly path A board a exists. find the path either of 2.11, square Figure in every boards through two the of each For Walks Board Z-tetrominoes 16 (e) T-tetrominoes 16 (d) xss fcus,n w ngt a vrocp h aesur of square same the occupy ever can knights two board. the sequence no such no course, that prove Of the or achieve 2.12 exists. Figure to of moves right of the sequence on upper shown shortest two position the the at Find are board. knights the black of two corners the and corners, bottom two the at f 5Tttoiosadoesur tetromino square one and T-tetrominoes 15 (f) 2.11 2.12 The squares. the all through path a find to boards Two orAtraigKnights Alternating Four (a) n > ihswt wthnx oec fte.Each them. of each to next switch a with lights 2 × hsbad h w ht ngt are knights white two the chessboard: 3 puzzle. (b) 43 Puzzles n cabbages, and n boxes with preset n are blue. The object is goats, 2 n n columns is filled with 3 < n wolfs, 1 n > are white, and 5 n 100 board to the diagonally opposite corner? < × 0 are red, n distinct integers and a sequence of n 2 identical-looking coins and a two-pan balance scale with counters of four types: > n n hunters. The object is to place the counters in a row such that no one is in inequality signs inserted between them,the numbers design into an the algorithm boxes that tonumbers satisfy places 2, those 5, 1, inequalities. and For 0 example, can the be placed in the four boxes as shown below: n danger; that is, no hunter is nextgoat to is a next wolf, to a no cabbage. wolf In is addition, next nobe two to next counters a of to goat, the each same and other kind no either. may How many ways are thereNumber to Placement solve the puzzle? Given a list of states of three lights:all its the own lights and are the off.flipping two Design the lights minimum an number algorithm adjacent of switches. for to turning it. all Initially theThe Other lights Wolf-Goat-Cabbage on Puzzle by You have 4 Lighter or Heavier? You have no weights. One of the coinslighter is or heavier a than fake, the genuine but coins, you whichan do all algorithm weigh not to the know determine same. whether Design in the it minimumthe is number fake coin of is weighings lighter whether or heavier than the others. A Knight’s Shortest Path What is the minimum numberfrom of one moves corner needed of a for 100 a chess knight to go counters, of which Tricolor Arrangement A rectangular board with three rows and to rearrange the counters tocolors have in counters every column. of The each only of operationthe allowed the same is three to row. swap different Design counters an in such algorithm an to algorithm accomplish does not this exist. task or prove that Exhibition Planning A museum has an exhibition spacepresented made in Figure up 2.13. There of is 16 a door rooms. betweenor Its every vertically pair floor adjacent of rooms. plan horizontally In addition, is each room onside the north of and the south building (the top andthe bottom outside. lines In of the planning plan) a has new one exhibition,of door the to the curator has doors to need decide which through to a be door on open the so northand that side, get visit a out each visitor through and a every can door roomwants enter exactly on to once, have the the as south exhibition few side. doors Of open as course, possible. the curator also 43. 42. 44. 45. 46. 47. Algorithmic Puzzles 44 FIGURE 50. 49. 48. b nwrtesm usini hr r 0bakblsad1 white 15 and balls black 20 are there if question same the Answer (b) the repeat You bag. a in balls white 16 and balls black 20 have You (a) get Ball Last six all crossings? can fewest the How with cannibals. river the by across present, outnumbered If boat. be the row cannot can people missionaries cannibal no with each itself and by missionary river Each the board. cross on can cannot boat it and Their people, river. two a hold cross only must cannibals three and missionaries Three Cannibals and Missionaries b eina loih ocmuetenme fbxso ahorder each of boxes of number the compute to algorithm an Design (b) a idaltepstv neesta are that integers positive the all Find (a) pieces. 20 and 9, 6, boxes adding 4, in of by come which obtained McNuggets, be Chicken can McDonald’s of that orders integer together positive a is number McNugget A Numbers McNugget niaealteetac-xtpista a eoe o h exhibition. the for open be can that pairs exhibition? entrance-exit the the for all open Indicate be to need doors exit the and for entrance open What be to (b) need that doors of number minimum the is What (a) 2.13 al osatwith. start to balls the bag? the to in ball left white ball last a the add of ball you color black the colors, a predict different you add of Can you bag. are color, they same the if remove of bag; You are the bag. they to If the time. in a left at is balls ball two single a until operation following iefraygvnMNge number. McNugget given any for size exhibition? lo lno 6rooms. 16 of plan Floor B1 A1 B2 A2 B3 A3 not cugtnumbers. McNugget A4 B4 45 Puzzles puzzle. =3 = 3 n 1 of them are genuine with − Counting Triangles n th iteration? n are shown in Figure 2.14. How many small n =2 = 2 n 1 squares by straight cuts along the grid lines. You and one of them—of an unknown weight different rectangular board drawn on graph paper. You need × , n 1 g × 1 identical-looking coins: mn m > n —is counterfeit. Design an algorithm that determines the fake in First iterations of the algorithm for the g 2.14 are allowed to stack several pieceswhich together is to considered cut one them cut. at Design thewith the an same minimum algorithm time, number that of cuts. performs this task Odometer Puzzle A car odometer can999,999, display inclusive. any six-digit If combination itcombinations from runs will 000,000 through have to its at entire least range, one how digit many 1 in such them? What is the total triangles will be there after the to cut it into a known weight from the minimum number of weighingsspring scale on indicates a the exact spring weight scale. of the (Assume coins being thatCutting weighed.) the a Rectangular Board There is an Fake-Coin Detection with a Spring Scale You have Missing Number Jill bets Jack that she can do thenumbers following from trick. 1 Jack to will 100 recite in 99 a different only random order number and in she that will be range able thatfor to he name Jill the will to have do missed. the What trick?head, is Of without the taking course, any best she notes. way will have to perform theCounting Triangles task in her An algorithm startssubsequent iteration adds with new triangles all a around thefor outside. single the The results first equilateral three values triangle of and on each =1 = 1 55. 54. 53. 52. 51. n FIGURE PUZZLES OF MEDIUM DIFFICULTY Algorithmic Puzzles 46 60. 59. 58. 57. 56. ie ih ssee ragemd of made triangle isosceles right a Given Triangle be Coin will a test? Squaring prisoners the pass the prisoners all the can do, How executed. they be If will they up. otherwise to line freed, have will same prisoners the those during only and forward the hat pass step black To a prisoners pm. with 12:55 the prisoners at the up ending all and line test, pm will 12:05 at warden starting The minutes 5 prisoners. every communications the no among be will kind there any own; able of their be but will hat They else’s fact. everyone this see about each to informed of be hat one will white, least prisoners or at the be black and will either There color, prisoners. hat, these a of each warden put of the will head them, the He on of test. rid following get the To with jail. up a comes in prisoners smart very 12 are There this? Colors do Two to of swapped Hats be to is have what will again, that row pairs each card sort of to number clubs decide largest you the say, If sort array. rule, Then new the (highest). predefined of spades column some and each Resolve by hearts, respectively). diamonds, rank 13, is by same 12, followed Ace the (lowest), 11, the of are cards (where King that among and value rank, ties Queen, cards’ numerical an Jack, the form their the by to of and row table 1, order each a Sort nondecreasing on columns. in up 13 face is and cards rows the 4 lay of and array deck 52-card a Shuffle Twice Sorting Once, Sorting year? a in there be will many How rabbits thereafter. of month pairs every and month second male/female the new of one end to the birth at pair give but life of month not first The are their wall. pairs during rabbit a fertile All by newborn. sides are all female) and on (male surrounded rabbits place of pair a initial in rabbits of pair a put man A Problem Rabbits Fibonacci’s stated? as recruits? order the arrange his stand you execute would men Schweik How remaining Did the order. let random in and them last, between one shortest the new first, the put recruit of Schweik tallest men. band adjacent to of sought a height in line difference up desired average The the line speech. minimize a to them gave ordered officer been their before had recruits Schweik soldier good The of reading Recruits next Up Lining the and 101,111 1’s, example, of (For more.) count four displayed? adds total 101,112 be the will toward 1 five digit contributes the times of number emvdt raeasur aeu faltecisgvn o many How given? moves? coins of number the minimum all the in of obtained up be can made squares square different a create to moved be n 2 n = − nFgr .5,wa stemnmmnme fcista edto need that coins of number minimum the is what 2.15), Figure in 3 dnia on,rsetvl sea xml fsc ragefor triangle a such of example an (see respectively coins, identical 1 n > ie otiig1 3, 1, containing lines 1 ... , 47 Puzzles 3. = n board, one coin per cell. m puzzle for × are written in a row. Design ” in front of them so that the n 4, there is one checker on each n − ≥ n ” and “ + -bit string (some sequence of 0’s and 1’s such as n Squaring a Coin Triangle 5) that we will refer to as a code. Your goal is to identify checkerboard, where = n n × consecutive integers from 1 to n Instance of the n 2.15 for which this can be done and indicate an algorithm that performs the expression obtained is equal to 0 or,the if message the “no task solution.” is Your impossible algorithm to shouldthan do, be an returns examination much of more all efficient possible ways to place the signs. Creating Octagons There are 2000 points inDevise an the algorithm plane, to no construct 250 three octagonspoints. of with Each their them vertices octagon on at has these the tocross same itself, be line. and no simple, two octagons that may is, have a its common point. boundaryCode should Guessing not Your friend thinks of an 01011 for square of its main diagonal fromone upper can left select to any lower pair right. of Onsquare, the each provided checkers move, this and will move not each move of amove them checker all off the down checkers the one to board. the The lowest goaln row is of to the board. Find all thetask. values Also determine of the number of moves made by yourPicking algorithm. Up Coins Some coins are spread in the cells of an the code by asking your friend questions. Each question will provide your A robot, located in the upper left cellof of the the board, coins needs as to collect possible as and many step, bring the robot them can to move the either bottom oneits right cell current to cell. location. the When On right the each or robot visits one a cellcoin. cell down Devise with from an a algorithm coin, to it find picks the upcan maximum that collect number and of a coins path the it robot needs to follow to doPluses this. and Minuses The Checkers on a Diagonal On an an algorithm that puts signs “ 64. 65. 62. 63. 61. FIGURE Algorithmic Puzzles 48 69. 68. 66. 67. 70. 71. icei iie into divided is circle A the of Sectors sum on Chips total inclusive. million, the a find to 1 calculator, from or integers all computer in digits a of help the Without such of Sum sequence Digit a this? by do to up way set best equally initial the is the them What in operations. in water the water in the water of all of amount containing amount minimum vessel a total achieve to the is object split The take them. and operation: between vessels following the the perform of to two allowed are You empty. others o aet pl h olwn prto 9tms eettoo the of two select times: 49 operation board, following the on the numbers apply to have You h rt5 aua ubr—,2, numbers—1, natural 50 first The Number Remaining the in any identify bits can same that n algorithm the an have Devise positions. strings fifth two and the third, second, because 3 11001, be is string should the question’s answer your in and the bits 01011 is corresponding code the the if with example, coincide For code. string your in bits many how an with friend | hr r 0ietclvses n fte with them of one vessels, identical 10 are There this in obtained Down Averaging be can that number remaining manner. the of values possible i h aeo poiedrcin) o hc ausof values which For sectors directions). neighboring opposite their to or chips same two the moving by (in made is move A them. hr are There I Pairs into Jumping sector? same the on chips the all collect to algorithm s eini hc hr sapt ewe n aro akdclsthat cells marked of pair any between path a is there that region, which contiguous in vertically, a region or form a must horizontally is, cells either marked other The each diagonally. not to but next are considered they are cells if Two neighbors neighbors. marked of number even positive a has Mark I Cells Marking such for moves of number minimum the in puzzle values the the all Any Determine allowed. ignored. are is of triples coins no adjacent coin; between single space next empty the previously on one or land coins to single pair), two over either formed left over or (i.e., right it jump to can adjacent coin coins single two a move each On moves. of sequence a btcd nn oethan more no in code -bit n − o hc h uzehsaslto n eiea loih htsolves that algorithm an devise and solution a has puzzle the which for b n | el na nnt he fgahpprs htec akdcell marked each that so paper graph of sheet infinite an on cells ntebad n hneaeboth erase then and board, the on n on lcdi o.Tega st form to is goal The row. a in placed coins n btsrn fyu hie n orfin iltl you tell will friend your and choice, your of string -bit a n and > n questions. etr,adoeci spae nec of each on placed is chip one and sectors, 1 b , rt h bouevleo hi difference their of value absolute the write ... 0aewitno board. a on written 50—are , a a and it fwtradthe and water of pints n / n ar fte ya by them of pairs 2 ’s. b . eemn all Determine n steean there is 49 Puzzles can this be done? can this be done? n n cells on an infinite sheet of graph paper so that each marked Four marked cells with an odd number of marked neighbors. Four marked cells with an even number of marked neighbors. n algorithm to do this in theexplain minimum why. number of moves. If he cannot, 4 is shown in Figure 2.17. For which values of 4 is shown in Figure 2.16. For which values of 2.17 2.16 = = goes through a sequence of marked neighbors.n For example, a solution for Rooster Chase This game is played onthe the lower grid left shown corner represents in a Figurecorner farmer; 2.18. the represents The R a counter F rooster. at counter The the farmer at until upper and the right the rooster rooster is move captured. alternately Onneighboring each point move, on each the of grid: themwhen up, can the farmer down, move can to left, move a on or a right. point occupied A by capture the(a) rooster. occurs Can the farmer catch the rooster if he moves first? If he can, provide an Marking Cells II Mark cell has an odd numberneighbors of if marked they neighbors. are next Twobut to cells not diagonally. each are The other considered marked either cellsis, horizontally must a form or region a vertically, in contiguous which region, that theregoes is through a a sequence path of between marked any neighbors.n pair For example, of a marked solution cells for that 73. 72. FIGURE FIGURE Algorithmic Puzzles 50 FIGURE 74. 75. h eurmnssae.I ti,poei;i ti o,fidtesots one. shortest the find not, is all it if satisfies it; that prove possible is, it tour If shortest stated. the requirements the is them.) this passes whether he is time every question stations The the visits inspector the that course, of n hng ostation to go station then to and 1 station from go might he osdrtegnrlcs fthe of case general the Consider Selection Site fcus,yusol sueta h ose sntgigt oprt in cooperate to going not is capture. rooster his the that assume should can, you course, he Of If second? moves he if rooster the catch farmer the Can (b) | iue11ai h rtttra o neape.Teojc sto is object The ( location example). a an find for to tutorial algorithm first (see an avenues the devise vertical in and 1.10a streets horizontal Figure with city planned perfectly hr emybtde o aet ns i or st ttos2through 2 stations to As tour. his station finish visit to n to have need not does also numbered but will may He he time. are where more one stations visit to need The will to highway. 1 straight from consecutively a along equidistantly a tto npco ed oinspect to needs inspector station gas A Inspections Station Gas h ahta itne rmtehue ota oain optdas computed location, that to houses the from distances Manhattan the hc sdsusdi h uoilo loih eintcnqe.Let techniques. design algorithm on tutorial the ( in discussed is which x x − 1 2.18 1 , − ,h ed oisette neulnme ftms o example, For times. of number equal an them inspect to needs he 1, y rvd nagrtmt oti ntemnmmnme fmoves. of number minimum why. the explain in cannot, he this If do to algorithm an provide 1 x nta oiino the of position Initial ) |+| , ( x 2 y , F 1 y 2 − ) .., ,... y |+···+| n ( x gi ocmlt i aktee I sassumed, is (It there. task his complete to again n n ose Chase Rooster h npco trsa tto ,wihhe which 1, station at starts inspector The . , y n x niaetelctosof locations the indicate ) n − x |+| eoaeSadPlacement Stand Lemonade n unbc n eunt tto 1, station to return and back turn , game. y n x − , n y iiiigtesmof sum the minimizing ) y > | . a ttoslocated stations gas 1 R n ossi a in houses n puzzle, twice, 51 Puzzles . n n )so × , you n n ... ,... , . 2 , 1 1111 square with straight = passes by the lockers, n i × n × n 1111 th pass, , chessboard? (Here, a tour does i n 111 for which a prince can visit all the × n n × is divisible by 3. Is it true that for every people is a person who knows nobody n 111 n 1 tile. Obviously, one can tile any , 1 tile called a monomino? If it is possible, 11 × × th locker: if the door is closed, you open it; if it × i 11 board exactly once on the same tour. , 1 n × × 1 lockers in a hallway, numbered sequentially from 1 to n n 3 that is not divisible by 3, one can tile an > not have to start andand end ends at are considered the “passed same over” by square; default.) the squaresSearching where for a it Pattern starts Perform the following multiplications: n square with straight trominoes if toggle the door of every is open, you close it.second Thus, pass, after you the only first toggle pass the every even-numbered door lockers is (#2, open; #4, on the trominoes and a single 1 explain how; if it is not, explain why. Locker Doors There are but is known by everybody else.asking The questions task to people is of to the identify form “Do aefficient you celebrity know algorithm by him/her?” to Design only an identify a celebrity or determine that the group has Celebrity Problem Revisited A celebrity among a group of that after the second pass theopen; even the doors third time are through closed you and close the thethe door odd first of ones locker pass), #3 are open (opened from the doorand of so locker on. #6 After (closed the from lastclosed? the pass, How second which many pass), of locker them doors are are open? open and whichThe are Prince’s Tour Consider a special chess piece—to be called here aone “prince”–that square can to move the right, or one squareupward downward, to or the one square left. diagonally Find allsquares of values an of Will the pattern you observestrings in of 1’s? the products continue if youStraight use Tromino Tiling longer A straight tromino is a 3 Efficient Rook The rook in chess canthe move same row either or horizontally vertically to tocurrent any any position. square square What that is that is the is in minimumrook in the to number pass same of over column all moves the as needed squares its of for an the Initially, all the locker doors are closed.each You time make starting with locker #1. On the 77. 80. 79. 81. 78. 76. Algorithmic Puzzles 52 FIGURE FIGURE ik rmtelf e otergtpeg. right the to peg left the from disks 84. 83. 82. hw nisac ftepzl for puzzle the 2.20 of Figure instance bottom. and an the the at shows pancakes biggest arrange the to the with is size of objective their to The one according spatula. pancakes under the above spatula stack whole a the slip over flip to allowed are You other. e rmv ikfo htpg(iue21) eina loih that moves. algorithm of an number minimum Design the 2.19). in (Figure puzzle peg the that solves from disk middle the a a on of move disk top or a on place peg disk either larger should a move place any to addition, In forbidden one. disk is smaller one it Only and peg. time, third a the at smallest to moved the disks be and the can all bottom transfer the to on is largest object the The top. size, on of order in peg first the on hr are There Sorting Pancake hr are There Hanoi of Tower Restricted case? worst an the moves. in Design of required number succession. are minimum moves the in many in How laying up heads coins coins the of all turn number to algorithm any over turn can one hr are There Up Heads algorithm your questions for of problem number the solve largest to the needs is What person. such no hspzl n eemn h ubro ismd yteagrtmi the in algorithm the by case. made worst flips of number the determine and puzzle this 2.19 2.20 ack Sorting Pancake Hanoi of Tower Restricted n n n on naln,hasadtisi admodr nec move, each On order. random in tails and heads line, a in coins ik fdfeetszsadtrepg.Iiily l h ik are disks the all Initially, pegs. three and sizes different of disks acks l fdfeetszs htaesakdo o feach of top on stacked are that sizes, different of all pancakes, uzefor puzzle n n uze rnfrtruhtemdl e l the all peg middle the through transfer puzzle: people? = n 7. = 7 . eina loih o solving for algorithm an Design 53 Puzzles 1 1 T + + cells n n T n B’s. In the T counters in n positions are n n 1 positions are + F n W’s followed by the first F , n 1 F counters in the last + positions of the board, except n n 2 1 cells, there are 1) 1 of them. Determine all values of rows, the first + + n − n n n ⇒ B’s. In row n F F positions are occupied by n F 1 columns. All the (2 people, each in possession of a different rumor. They want people, each in possession of a different rumor. They want + glasses on the table, all standing upside down. In one move, cells representing Toads and T n n the task can be depicted by the following diagram: n n , n 3 T rows, the first = n n for which all the glasses can be turned up, and outline an algorithm that T occupied by W’s followed by one vacant position followed by to share all thevia rumors through a a telephone). series Deviseconversations) of an algorithm bilateral for efficient conversations this task. (in (e.g., Assumeboth terms that parties in exchange of all every the the conversation rumors they total know at number theUpside-Down time. of Glasses There are you are allowed to turn over exactly B’s. The W counters can move horizontallycounters right can or move vertically horizontally down; left the or B verticallya up. slide to A move the can empty be neighboring either position or a jump over one counter of rows and 2 last occupied by W’s followed by n does this in the minimum number of moves. Toads and Frogs On a one-dimensional board with 2 to share the news withis each the other minimum by number sending of electronic messageseveryone messages. they of What them need gets to all send the rumors? to Assumerumors guarantee that he a that or sender includes she all knows the at themay time only the have message one is addressee. sent and that a message Rumor Spreading II There are the central one, are occupiedand by black counters (B), as of follows. two In colors, the say, first white (W) Devise an algorithm to accomplish this task. Counter Exchange This solitaire game is played on a two-dimensional board with 2 Rumor Spreading I There are representing Frogs. Toads and Frogs take turnssliding moving. a Moves Toad consist or of Frog intocreature the empty to cell the or jumping emptyneither over can one cell. Frogs.) opposing Toads (Toads can only cannot moveleftward. rightward; jump The Frogs object can over is only to move themselves makefor them and switch their positions. For example, the first 87. 88. 86. 89. 85. Algorithmic Puzzles 54 FIGURE FIGURE 90. 91. 92. W W W W W W W hr sarwof row a is There Rearrangements Seating oo seFgr .1for opposite 2.21 the Figure of (see counters color the by the occupied all initially switch positions to the is can to object counter The counters color. No same it. the of beyond counter right another over position jump empty the to color opposite the oms qiaea ragei hpe f iligargo uha the as for such 2.22 region Figure a in yielding shown off one chopped is triangle equilateral topmost eemn l h ausof values the all Determine Dominoes Vertical and Horizontal children two by seats? made exchanging is other each another to to next arrangement sitting children one the from of transition arrangements a seating if possible all getting for algorithm an aalllnsdvdn aho t ie into sides its of by triangles each equilateral dividing smaller lines into parallel partitioned is triangle equilateral An Tiling Trapezoid same. the is dominoes vertical and horizontal of number the 2.21 2.22 W W W W W W W The eint iewt rpzi ie i ry for gray) (in tiles trapezoid with tile to Region W W W W W W W one Exchange Counter W W W B B B n B B B B B B B hisocpe by occupied chairs B B B B B B B n n = uzefor puzzle B B B B B B B o hc n a iean tile can one which for o nillustration). an for 3 n = .Ti einnest etldwith tiled be to needs region This 6. n = n B B B B B B B hlrn si osbet design to possible it Is children. 3. B B B B B B B n > n qa emns The segments. equal 1 B B B B B B B = 6. n B B B W W W × n or othat so board W W W W W W W W W W W W W W W W W W W W W 55 Puzzles (Figure 2.23 for n S 2 weighings. − 2 10 board? The battleship can be / n × 3  for which this can be done and devise a tiling n to be tiled with right trominoes (in gray). 1 for which a staircase region 8 S > ’s. n n 1 rectangle) on a 10 × 1 items and a two-pan balance scale with no weights, determine > Staircase region n 8) can be tiled with right trominoes? 2.23 = Tiling a Staircase Region Find all values of n located anywhere on the boardor and vertically. You may may be assume oriented thatblind there either guess are horizontally of no a other square on ships. the (A board.) “shot” is a Searching a Sorted Table One hundred different numbers are written oncard. 100 cards, The one number cards per areorder arranged in in each row 10 (left to rows right) andare and each column 10 turned (top down). columns, faced All the in down cards them. increasing so Can that you devise you an cannot algorithm tois see written determine on the whether one a numbers of given the number written cards by on turning upMax-Min less Weights than 20 cards? Given the lightest and the heaviest items in trapezoid tiles made of threesmall equilateral triangles triangles of composing the the samesame size region. way, as (Tiles but the need they need notDetermine to all be cover values oriented of the the region exactly with no overlaps.) algorithm for such Hitting a Battleship What is the minimumbattleship number (a 4 of shots needed to guarantee hitting a The Game of Topswops Consider the following one-person card game. It isthe played same with suit; 13 each cards card of is considered as having a numerical value: the ace 96. 94. 95. 93. 97. FIGURE Algorithmic Puzzles 56 FIGURE 99. 98. niaea loih ihtemnmmnme fexchanges. of number minimum the possible, with is algorithm it an When indicate operations? such of sequence a with order increasing in o r loe oecag n aro ad hthv xcl n card one exactly have that of cards values which of For pair them. between any exchange order. to decreasing allowed in sorted are are You numbers the that so card) per number (one nrvreodr neapeo h aesse ssonbelow: shown is there step returned game’s then the of and example deck An the order. from reverse removed in are card, top the of value hr are There Sort of Reversal rrgttruhajcn etr.Tesm etrcnb sdmr than left, sequence. more same down, used the step—up, be in each can once letter on same direction The any letters. in adjacent right—through You go or and 2.24? W Figure any in at shown start arrangement may diamond-shaped the in read be palindrome the can ways different many how In every for Counting iterations Palindrome of number finite deck? a the of after state initial stop always game the Does p fi steae h aesos tews,tetop the Otherwise, stops. game turned the is ace, deck the is the it of If card 12, up. After top 11, The shuffled. repeated. are are is king cards operation and following the the queen, begins, that jack, game the the where Before on, respectively. so 13, and and 2, is deuce the 1, is 2.24 etrarneetfrthe for arrangement Letter 5710K8A3Q J4926 n W ne ad narw with row, a in cards index A W W W W A S A W S S W A A I A TACTISAW I CAT A IT WAS A I W I W A S T S W W A S I T T A I S A aidoeCounting Palindrome A ⇒ A S I C T I S A W A T n si osbet aetecrssorted cards the make to possible it is T T W W A S I A I S A n 8K1075A3Q J4926. itntitgr rte nthem on written integers distinct I I W A S W S A T W W A S A I S W W A A S puzzle. n W W A ad,where cards, W n sthe is 57 Puzzles moves on an n puzzle. 8 chessboard, with each of the 64 rooms having a door × 6 board, the 15 positions shown in black in Figure 2.26 are Room Painting × The 2.25 in each of itspainted four white. walls. Then Originally, the all kingthey the ordered alternated floors like the the in floors squares all of tohis a the be painter chessboard had rooms repainted (Figure to walk 2.25). so were through To the that do palace repaintinghe this, floors visited in from all the white rooms to black,exit and the vice palace versa. and The reenter painter it wasthe at allowed order another by to repainting door. the Was rooms there not a more way than 60 to times? execute infinite chessboard? (The knight’s moves are L-shaped: twoup, squares down, either left, or right and then one square inRoom a Painting perpendicular direction.) There once lived a king who likedmimicked chess. an He 8 had a palace whose floor plan occupied by counters. The task is to move all the counters, which are The Monkey and the Coconuts Five sailors and a monkey were shipwrecked onfirst a day, desert they island. During collected the some coconutsone to sailor eat woke the up, next divided morning. theone At coconuts coconut night, into to five the equal monkey, hid pilesand his after went pile, giving back recombined to the sleep. other Later fourthe that piles, same night, thing each one of after the the otherand other: four then each sailors took gave did one-fifth one of coconut the to remainingthey the ones divided monkey for all the himself. remaining In coconuts the among morning, themselvescoconut after to giving one the monkey for the lastcoconuts time. that What could is have the been in minimum the number original of pile? Jumping to the Other Side Ona5 A Knight’s Reach How many distinct squares can a chess knight reach after 101. 103. 102. 100. FIGURE Algorithmic Puzzles 58 FIGURE 105. 104. si osbet bantesrn Uuigteerules? these using MU string the obtain to possible it Is following the applying times: then of number and be finite MI can a rules that string transformation U the and with I, starting M, by symbols obtained three the of composed strings Consider Puzzle MU The b o osteslto otepzl hnei eaet opt the compute to are we if change puzzle the to solution the does How (b) a Given (a) Splitting Pile eodi.Jmsmyb oiotl etcl rdaoa naydirection. any accomplished? in be diagonal task or this vertical, Can horizontal, be counter may a immediately Jumps move, position it. unoccupied each beyond an On to counter line. adjacent the an over below jump positions can the to line, the above ue4 eoeayU,freape hnigMU oMU. to to MUUU MUIIIU changing example, changing for UU, example, any Remove for 4. Rule U, a with III MUUU. for any Mxx), Replace to 3. Mx change Rule is, (that MIUIU. M to MIU the changing after example, string any Double changing 2. example, for Rule I, in ending string MIU. any to of MI end the at U Add 1. Rule 2.26 vr pi n aeaga fmxmzn h oa fsc sums? after such obtained of total piles the two maximizing of the goal in a have counters and split the every of numbers the of sum sum maximal this is What to? products? equal the of sum the maximize to piles are ie band otnet pi ahpl notosalrplsand piles are there smaller until two products into the two compute pile the to each in split counters to the Continue of obtained. numbers piles the of product the compute and h or fthe of board The n ie,smaltepout optd o hudoesltthe split one should How computed. products the all sum piles, n onesi ie pi h onesit w mle piles smaller two into counters the split pile, a in counters upn oteOhrSide Other the to Jumping n ie fsz n.Oc there Once one. size of piles puzzle. 59 Puzzles domino set. n . The game is posts, located at n They move alternately, . 1 > ). domino set. n s , n n The Fox and the Hare for which the fox can win the game. s switches in such a way that it lights up n ” domino set would consist of domino tiles for each n domino set or prove that no such algorithm exists. n A chip representing the fox starts at cell 1, and a chip . Dominoes n (Of course, every pair of adjacent tilesnumber in of the spots ring on must their have adjacent the halves.) same in a double- (c) Design an algorithm for constructing a ring made up of all the tiles equal distances along a straight road,post the and best put way the notes is as to one startWhat passes with would the the posts be until first the the worst last (i.e., onenot is longest) required reached. way to to start accomplish this atturns task? the must It be first made is post at the and posts. end atDouble- the last one, but allDominoes the are smallembossed rectangular at both tiles halves with ofgames the involving dots patterns tiles. called on They a areset spots tabletop. has used A 28 or to tiles: standard one play “double-six” for pips each a domino In unordered variety general, pair a of of “double- values from (0, 0) to (6, 6). unordered pair of values from (0, 0) to ( (b) Find the total number of spots on all the tiles of a double- (a) Find the number of tiles in a double- The Longest Route If someone wants to attach a copy of a note to each of with the fox moving first. On eachneighboring move, the cell; fox the can hare move jumps left left or orthird. right right to The over a hare two cannot cells landing land onhave on the another a move, cell he loses occupied the by game.move And, the outside of fox; the course, board. if neither The fox’s of he goal them does is can toif not catch they the hare, occupy which adjacent he can cells do onthe the capture. fox’s Find move; all the the values hare’s of goal is to avoid The Chameleons A researcher puts three typesgray, of and chameleons 15 on black. an When island:both two 10 change chameleons brown, their of 14 different colors colors tochameleons meet, to the become they the third same one. color? Will it be possible for all the representing the hare starts at some cell Turning on a Light Bulb A light bulb isonly connected when to all the switches arebutton; closed. pressing Each the button switch toggles is the controlled switch, by butthe there a state is push no of way the to switch. know Designthe an minimum algorithm number to of turn button on pushes needed the in light the bulb worst with The case. Fox and the Hare Consider a chase game that we call played on a one-dimensional boardfrom1to30 with 30 cells numbered left to right 109. 108. 110. 106. 107. Algorithmic Puzzles 60 FIGURE PUZZLES HARDER 112. 111. 113. idaltevle of values the all Find Revisited Tiling Domino position. moves. new minimum its of to number time the a for at formula coin compact of one a number slide Give minimum can you the move in each down on if upside moves triangle the Design flip lattice.) to triangular equilateral algorithm the an of points coins the the at of be centers to (The assumed 2.27. are Figure in shown one the other like or coins pennies identical packed closely by formed triangle equilateral an Consider Triangle Coin a Inverting qae fopst ooscnb ie ih2 with tiled be can colors opposite of squares eo.(h edu onbigrmvdi hw nbold.) in shown shown is line removed coin being the coin head-up for after (The puzzle coins below. the two solves moves between of gap example, sequence For following a “neighbors.” the considered is longer no there are if coins the line; moves, to some original next are the they in if other “neighbors” considered each are can any, Coins if one is coins, over. move, or turned puzzle each coin be the neighboring On must its moves. of which of after object coin, sequence The head-up a any order. by remove coins particular the no all in remove up, to tails are rest the hr saln of line a is There Removal Coin 2.27 qiaea rageo on oinvert. to coins of triangle Equilateral n on ntetbe oeo hmaehasu and up heads are them of some table; the on coins H T THHT n ______T __ __T o hc an which for H _TH_TH H H TH HH_ H __TH n × H _TH n hsbadwt w missing two with chessboard H HH × dominoes. 1 H _ 61 Puzzles , n 2 > n so that it would be } consecutive horizontal n n w ,... , 2 w , 1 w { , assuming the following: 2 straight lines without lifting your pen W − n weights n point lattice (intersection points of n × n Crossing 16 points by 7 lines. consecutive vertical lines on common graph paper), where 4, shown in Figure 2.28, has seven lines instead of the six required by the number ofpower players of 2. left for the secondeven round number of is players in that equal round. to a n = 2.28 and from the paper. You maycannot cross the redraw same any point portion moren than of once, the but you same line. (A “greedy” solution for possible to weigh onlargest possible a range from two-pan 1 to balance scale any integral load in the Bachet’s Weights Find an optimal set of (a) Weights can be put(b) only on the Weights free can pan be of put the on scale. both pans ofBye the Counting scale. If a single-elimination tournamentnot starts equal with to the a numberare power of transfers of players 2, of some playersno players directly opponent need to assigned to be the toin given such next them. byes, a round Determine which tournament because thebelow. under they the total two have number different of definitions of byes byes(a) given Byes are given to the fewest players(b) in the Byes are first given to round the fewest players so in each that round so that there is an cross out all the points by 2 Determine the property of the starting linefor that the is puzzle necessary to and sufficient have athe puzzle’s solution. rules, For design those an algorithm lines for that doing can so. beCrossing removed Dots by Given an the puzzle.) 115. 116. 114. FIGURE Algorithmic Puzzles 62 FIGURE 119. 117. 118. 120. eiea loih o h olwn ak ie 2 a given task: following the for algorithm an Devise Tiling Tromino Colored array an on played solitaire of peg of version one-dimensional the Consider Solitaire One-Dimensional hr r i ngt na3 a on knights six are There single the Knights Six of locations corresponding the and peg. solved remaining which for such be setup of initial can sequence the in puzzle a cell by the empty peg the of one locations but the all all Find on remove moves. to land from is removed to object is right The neighbor the jumped-over board. the to the jump, or the left after cell; the empty to peg an a neighbor move, immediate each On its cell. over per jumps peg one (pegs), counters some by occupied mcie ossso o fbxs osat n places one start, To boxes. of row a of consists “machine” A Machine Distribution Penny squares Recall adjacent color. three 1.4). same by Figure formed the (see tile have L-shaped an edge is an tromino right share the that that so trominoes colors of three only pair of no trominoes right that with it tile square, missing one with h ngt ogttepsto hw ntergto iue22 nthe in 2.29 on time. Figure knight any one at of than square right more a allowing the not moves, on knight shown of number position minimum the Exchange get row. top to the at knights are the knights black three the and row, bottom the at h etotbxwt tlattocoins. two in least pennies at of with pair box a the leftmost selecting of the always work by the pennies shows six 2.30 distributing single Figure in a example, box machine no For with is coin. there box one when one stop than iterations more in The with right. pennies the to of box pair next the a in follows. penny replaces as it pennies iteration, the redistributes each then On machine The box. leftmost the 2.29 n el,where cells, The i Knights Six n see n rae hn2 ntal,albtoecl are cell one but all Initially, 2. than greater and even is puzzle. × hsbad h he ht ngt are knights white three the chessboard: 4 n × 2 n ( n n > ene in pennies )board 1) 63 Puzzles n clips, n 1 1 3 2 1 1 paper clips. What is the minimum number > n 0 0 2 6 4 checkers of three colors: red, white, and blue. Devise n Example of penny distribution. the machine processes the coin pairs? pennies? 2.30 (c) How many iterations does the machine make before stopping? inclusive, from the resulting pieces? (b) What is the minimum number of boxes needed to distribute (a) Does the final distribution of pennies depend on the order in which of single clips that mustpossible be to removed create from a the chain chain so of that any it integer would length be between 1 and Super-Egg Testing A firm has invented ato super-strong determine egg. the For highest publicity flooran purposes, egg in it can a wants fall 100-story without breaking. buildingeggs The to from firm experiment has which with. given Of such course, a the testertimes same two unless egg identical can it be breaks. dropped What multiple isguaranteed the to minimum determine the number highest of safe droppings floor that in all is cases? Parliament Pacification In a parliament, eachthat member enmity has is at always most mutual.)parliament three into True enemies. two or (We chambers false: assume in onemore such than can a one way enemy always in that divide his no or the her parliamentarian chamber? has Dutch National Flag Problem There is a row of an algorithm to rearrange thefirst, checkers so all that the all white the onesThe red come checkers only come next, operations and allowed allswap are the of examination blue two of checkers checkers. come ayour Try algorithm. last. checker’s to color minimize and the number ofChain Cutting swaps made by You have a chain of 122. 123. 121. 124. FIGURE Algorithmic Puzzles 64 130. 129. 126. 125. 127. 128. b a h igaheehsga ihjs ih slaves? eight just with goal his weeks? achieve 5 king in the scheduled Can feast a before (b) done be to this Can prepared is (a) king The barrel. poisoned been days. the determine 30 has to exactly slaves barrels his in of wine 10 person sacrifice matter 1000 a no it, his kills of amount diluted, of miniscule a how one that potent that so is poison informed The poisoned. is king evil an An Devise one. smaller a Wine Poisoned of top and moves. on 33 time, in disk a puzzle larger the at solves moved a that another be algorithm place can the to to disk disks and forbidden one the bottom is Only all the moves. it transfer of on to sequence largest is a the by objective size, peg The of top. order the in on disks peg smallest the all first Initially, the pegs. four on and are sizes different of disks eight are There Puzzle Reve’s moves. one of number considered minimum is the switch find one Also move.) (Toggling in on, moves. all of initially are number which minimum switches, the the all off turn to algorithm an Devise time. a at toggled be may switch one Only (iii) nrne h wthscnb aiuae sfollows: as manipulated be can switches The entrance. hr are There Fairly Cake a Dividing making weights, their of weighings. order seven than increasing more with in no scale items balance the two-pan Order a weights. and weights no different of items five are There 7 in 5 Sorting si osbefraceskih ovstalteclso n8 an of cells the all visit to knight chess a for possible it Is Tour Knight’s The this for algorithm an Devise gets. he task. portion the with satisfied is everyone hr sarwof row a is is There cell a Switches that Security Note it over passes just re-entrant. not it, move.) or its on on lands closed starting knight the called the when from only is visited away considered tour move knight’s a one (Such cell cell? a at ending once, exactly i)Ayohrsic a etre no f nyi h wtht its to switch the if only off or on turned be may switch other Any (ii) i h ihms wthmyb undo rofa will. at off or on turned be may switch rightmost The (i) meit ih so n l h te wthst t ih,i any, if right, its to switches other the off. all are and on is right immediate n > red h att iieack mn hms that so them among cake a divide to want who friends 1 n euiysice rtcigamltr installation military a protecting switches security × chessboard 8 65 Puzzles ... BW. moves n ... (b)(b) BWBW puzzle. (a) Advancing a peg to one row. (b) Solitaire Army counters with no spaces between adjacent counters. n . 3 (a)(a) B. The counters are to be moved in pairs; on each move, a pair ≥ n ... Solutions to the 2.31 The objective is to rearrangeare the before all counters the so black that ones with all no the gaps white between the counters counters: W W The counters alternate between black and white: of adjacent counters can bevacant moved, location. without Design changing an their algorithm order, thatfor into any solves a the problem in The Game of Life This solitaire game issquare “played” cells. on Each an oflive infinite the or two-dimensional cells dead. grid is Afterfor of always some example, in initial by one configuration of of marking live two them cells possible with is states: a selected— black dot—a sequence of new The Solitaire Army This variation of pegboard solitaire with is a played horizontal on lineinitial an separating position, the infinite a board two-dimensional number intoare two of placed halves. pegs below In (the this an line. “soldiersarmy’s The of “scout”) object the as is far to solitaire above advance army”) jumps. the one On of line each the as move, pegs a possible peg (the by jumpsor horizontal over horizontally or its to immediate vertical land neighbor on vertically anneighbor empty is cell; removed after from the the jump, board.cell the in jumped-over For the example, first to row advance above aadvance the a peg line, peg to two to a pegs a cell will in sufficesufficient the (Figure (Figure second 2.31a); 2.31b). row, four to pegs are both necessary and Find an initial configuration of the following: (a) 8 pegs to advance(b) 1 peg to 20 a pegs cell to in advance the 1 third peg row to above a the cell line in the fourth row above the line Tait’s Counter Puzzle There is a line of 2 WBB 133. 132. 131. Advancing a peg two rows above the “enemy” line. X denotes the target cell. FIGURE Algorithmic Puzzles 66 134. 135. 136. eina loih o h olwn ak Given task. following the for algorithm an Design Coloring Point oscillate will that cells live of configuration initial smallest the Find remain (b) will that cells live of configuration initial smallest the Find (a) (iv) (iii) time, in step are each that At occur: cells transitions diagonally. following the or the are vertically, horizontally, which it neighbors, to eight generation. adjacent its current with the rules, interacts in cell cell following every Every the to simultaneously by applied obtained are which is “generations” called configurations eina loih o hsts ota o 2 for that so task this for algorithm an Design 2 arrange to has teacher kindergarten A Pairings Different line the on one. points by differ white or line, and same every the black either for of are that numbers so the white, and vertical, black or say, horizontal colors, two in them paint grid, nacmue ae p slctdo n-iesoa ie ttm 0, time At location line. at one-dimensional a is on spy located the is spy a game, computer a In Spy a Catching same. the nte oaino orcoc.Dvs nagrtmta ilfidtespy the find questions. or will number same that finite the a algorithm after at an is Devise spy choice. the the your whether if of time goal; location next another your the reach ask can you you “yes,” a “no,” is receive is answer will answer you the which If to answer. can 19, yes/no location you truthful at example, currently For is the choosing. spy whether your the 0) of whether ask location time spy’s some at at the (starting currently identify interval is to time spy is each goal at Your asking you. by to location unknown are they but integers, h ih if right the c idtesals nta ofiuaino ieclsta ilmv itself move will that cells live of configuration initial smallest the Find (c) (ii) (i) costebad Sc ofiuain r ald“spaceships.”) called are configurations (Such board. the across “oscillators.”) called are configurations (Such states. two between “still called are configurations lifes.”) (Such generation. every with same the iecell. live Birth generation. next the dies. neighbors overcrowding by Death dies. neighbors underpopulation by Death Survival b n edcl iheatytrelv egbr eoe the becomes neighbors live three exactly with cell dead Any ≥ ,and 0, n iecl ihtoo he ienihoslvso to on lives neighbors live three or two with cell live Any a ihec ieitra,tesymoves spy the interval, time each With . | b | nt otelf if left the to units n iecl ihmr hntrelive three than more with cell live Any n iecl ihfwrta w live two than fewer with cell live Any n hlrnin children b n < − 0 n asn arwudbe would pair no days 1 . rirr onso the on points arbitrary Both n ar o al walks. daily for pairs a and b b r fixed are nt to units 67 Puzzles 3. > n 2. You may / n chessboard so 2 pairs of them ’s. 2 coin pairs are n / n / n n × n 2 moves / n queens on an standing in a circle. Starting the count n n 2 knights around his Round Table so that children sitting in a circle facing their teacher > n n coins placed in a row. The goal is to form people numbered 1 to for which the problem has a solution and design an algorithm n n n -Queens Problem Revisited n with person number 1, everyperson second is person left. is Where in eliminated the until circleperson only standing? should a one person stand to remain the last Twelve Coins There are 12 coins identical in appearance; eitherone all of are them genuine is or fake. exactly It is unknown whetherthan the the fake coin genuine is one. lighter or You heavier haveThe a problem two-pan is to balance find scale whether without all weights. the the fake coins coin are and genuine establish and, whether if it not,ones. is to lighter find Design or an heavier algorithm than the to genuine solveof the weighings. problem in the minimum number Candy Sharing In a kindergarten, there are The Josephus Problem There are by a sequence of moves. Onone the first coin move adjacent a to single coinover it, has two on to adjacent jump coins, the on over second thethree third move move adjacent a a coins, single single and coin coin so has on, to has jump until to over after jump formed. (On each move, a coin cana jump single right coin. or Jumping left over but a itAny has coin empty to pair land counts space on as between jumping adjacentvalues over coins two of coins. is ignored.) Determinethat all solves it the in the minimum number of moves for those in the center. EachWhen child the initially teacher blows has a an whistle,his each even or child her number simultaneously candy gives of pieces to half candy the of with neighbor pieces. an on odd the number left. of Any pieces child isthe who given teacher ends another blows up piece her by whistle the again, teacher.number unless Then of all candies, the children in have whichforever the or case same will the it eventually game stop stops. to let Can the children this go gameKing on Arthur’s with go Round their Table lives? on King Arthur wants to seat that no two queens arelinear-time algorithm in for the finding a same solution row, to this column, problem for or any diagonal. Design a none of the knights is seated next toif his enemy. the Show number how of this can friends be for done each knight is not smaller than assume that friendship and enmity are always mutual. The Consider the problem of placing Jumping into Pairs II There are 142. 138. 140. 141. 137. 139. Algorithmic Puzzles 68 FIGURE FIGURE 145. 143. 144. hsfmu uzecnit ffite qaetlsnmee rm1to 1 from 4 numbered a in tiles placed square are fifteen which of 15 consists puzzle famous This Puzzle Fifteen The an of squares through spreads virus A Chessboard Infected odr fte1 the of borders r ree eunily si osbet ov h uzefrteinitial the for tiles puzzle the the which solve in 2.33? to Figure configuration in possible shown the configuration it into Is time sequentially. a ordered at are one arrangement them starting given sliding a from by tiles the reposition to is goal The empty. osdran Consider Squares Killing board? entire the to spread be to to virus need the that for squares initially unit infected of number not minimum but the vertically, is or What (horizontally diagonally). neighbors infected two has that square loih ormv h iiu ubro otpcsta ilbreak size. will any of that square toothpicks every of of perimeter number the minimum the remove to algorithm 1 9 5 1 2.32 2.33 3 nta n nlpstoso the of positions final and Initial 4 The 1 1 6 2 0 5 × n 1 1 or o the for board 4 × 3 7 × 4 1 n qae seFgr .2fra xml) einan Design example). an for 2.32 Figure (see squares 1 or omdb 2 by formed board 1 4 8 2 × iln Squares Killing o evn n qaeoto h sixteen the of out square one leaving box 4 ite Puzzle Fifteen n n ( × n puzzle. n + 1 hsbadb netn any infecting by chessboard 9 1 5 )tohik htsreas serve that toothpicks 1) 3 . 1 1 6 2 0 4 1 1 3 7 5 1 1 4 8 2 69 Puzzles consecutive n 1 mathematicians. > n which is composed of the , n S 1 hiding spots located along a straight line in which the target 1, inclusive, on the party hats the mathematicians are wearing. > 8 board with one coin on each cell, some tails up and the others tails − n n × down. While B is absent, the jailer pointshas out selected to to A be the guessed board’s by cell B. theone Prisoner jailer coin A on is the required board to before turn leaving overthe the exactly selected room. cell. Then A B and enters B and are guesses allowedthere to should plan their be strategy no beforehand, but communication betweenOf them course, B after is the allowed game to begins. seeto the perform board any after calculations he he may enters wish the tofreedom room do. or and Can is even the the prisoners game win impossible their to win? Pebble Spreading Consider the following one-person game that is played onobtained an infinite by board dividing the firstsingle quadrant pebble placed into at square the corner cells.can of It the replace starts board. a On with each pebble a move,one by the immediately player placing to two the right pebbles andthese in the two the other cells cells immediately are above, adjacent provided pebbles empty. to from a The it: staircase object region of the game is to remove all the The numbers may but need notwritten be on all all different. the After hats seeing but theamong their numbers themselves own, or with anyone no else, communication each whatsoever number mathematician on will write a his piece hat’s of paperof and them give it will to see thethe the president. numbers Of numbers course, is written none correct,will by they increase the win the others. their next If collectiveIf year’s at bet none budget least and of for the one them their president 5 of department guessed years. by right, Are 5 the the percent. the mathematicians budget bet? bluffing will or be do frozen they for have a theOne Coin way next for Freedom to win A jailer offers to free twoB—if imprisoned they programmers—we manage call to them win A thean and following 8 guessing game. The jailer sets up They conspired to challenge the university’s president,the who party, also to attended the following bet.0to The president will write any number from diagonals at the board’s corner (see Figure 2.34 for examples). can hide. The shooter cantarget never moves see to the an target; adjacentshots. all hiding Design an he spot algorithm knows between that is guarantees every hittingno that two the such the target algorithm consecutive exists. or prove that Hats with Numbers At a university-wide New Year’s party, there were Hitting a Moving Target A computer game has a shooterany and of a moving target. The shooter can hit 149. 148. 147. 146. Algorithmic Puzzles 70 FIGURE (shaded). FIGURE o (a) for 150. oiinfrees position k Take Solitaire Bulgarian of values the all Find for example, For n 2.34 2.35 o oepstv integer positive some for = ,(b) 1, n is oei the in move First the of positions Starting on where coins n = S 1 (a) ,ad(c) and 2, Fgr 2.35). (Figure n = n n 1 o hc h aesojciecnb achieved. be can objective game’s the which for , satinua ubr(i.e., number triangular a is h rtadol osbemv rmtestarting the from move possible only and first the ebeSpreading Pebble n = k ebeSpreading Pebble 3. ,addvd hminto them divide and ), (c) aefor game game (b) n n = = s re staircase frees 1 ≥ 1 + ie,with piles, 1 2 + ... + S 1 71 Puzzles k coins is, the process will always arrive at coins, respectively, after a finite number of n k example. ,... , 2 , Bulgarian Solitaire 2.36 piles containing 1 no restriction on thepiles. number Then of perform piles repeatedlyfrom the or each following the pile operation. numbers and Take ofwhat put one the coins all coin initial of in partition them the of in a new pile. Show that no matter iterations. (After reaching this state,in the it.) algorithm For will example, Figure obviously 2.36 remain illustratesdivided the into process two for piles 10 of coins 6 initially does and 4 not coins. Note distinguish that the sincenonincreasing Bulgarian pile order solitaire of order, their size, it as Figure is 2.36 does. convenient to list the piles in FIGURE 3Hints

1. A Wolf, a Goat, and a Cabbage With one insignificant exception, the puzzle can be solved by making a sequence of the only moves available in each situation. 2. Glove Selection Imagine a malevolent adversary who wants you to draw as many gloves as possible before getting what you need. Note that gloves are not socks: they can be right-handed and left-handed. 3. Rectangle Dissection Triangles in question need not be of the same size. 4. Ferrying Soldiers Solve the problem of ferrying one soldier first. 5. Row and Column Exchanges The answer is “no”; determine why. 6. Predicting a Finger Count Reenact the girl’s count long enough to see a pattern that makes the answer obvious. 7. Bridge Crossing at Night The answer is “yes,” and the solution does not involve any tricks. 8. Jigsaw Puzzle Assembly A similar problem is discussed in the book’s tutorial on algorithm analysis techniques. 9. Mental Arithmetic There are at least two different ways to compute this sum. Both use the methods discussed in the tutorial on algorithm analysis techniques.

72 73 Hints for which no such n Observe the colors of the squares the Advance toward the goal two checkers at You may manipulate the index given in “Three” is not the correct answer to the What parts of the board do you have to cut to Use the dynamic programming strategy. For each of the pieces except the rook, the The answer is “one.” Take advantage of the fact . The answer is “no.” 1 There are just a few values of Keep in mind that your path does not need to traverse What is the fastest way to make three pancakes? Also Derive a formula expressing the total number of digits ≥ Only one of the three questions has a “yes” answer. A required ordering can be easily obtained by one of the The puzzle statement does not forbid the king to visit the n Use dynamic programming as explained in the tutorial on It might be easier to find the number of “words” following 1 is, in fact, a special case here. = n King’s Reach same square more than once. Also,for make every sure value of that your answer is correct A Corner-to-Corner Journey knight jumps through. Page Numbering solve the puzzle? Tromino Tilings Making Pancakes note that as a function of the number of pages. Maximum Sum Descent Square Dissection algorithm design strategies. Chessboard Reassembly every edge; it just needs to visithere, but all prepare the to vertices. be You lucky may or use very backtracking patient. A Fake Among Eight Coins Blocked Paths alphabetical order. Find the Rank TURING. The Icosian Game puzzle. A Stack of Fake Coins that the scale gives the exact weight. Questionable Tiling dissection exists. Also note thatsize. smaller squares need not be of theTeam same Ordering solution can be foundstrategy. A simple by solution for a the rook straightforward is not application hardThe to find of Best either. the Time greedy to Be Alive algorithm design strategies outlined in the first tutorial. Polish National Flag Problem a time. Chessboard Colorings 17. A 19. 18. 15. 20. 16. 21. 14. 26. 27. 10. 13. 11. 12. 22. 25. 23. 24. Algorithmic Puzzles 74 31. 30. 29. 28. 33. 32. 42. 36. 35. 34. 46. 45. 44. 43. 41. 40. 39. 38. 37. a,a,a2, a1, say, Trick Pile Three The Stick a Cutting strategies. design algorithm on tutorial the in Revisited Square Magic puzzle this to key the is that well. insight as the on based is techniques analysis on Tracing Figure ai n Pseudo-Magic and Magic n Tournament Single-Elimination uzefor puzzle Puzzle the Wolf-Goat-Cabbage see Other to The help should puzzle the of instances difference. small few a Considering n iie Diversity Limited Jugs Three on tutorial design. the algorithm in for mentioned strategies method general strings” and “buttons the using by or Star a on Coins ih a omauetedsac ewe h tr n ns squares. Arrangement finish Tricolor and start the between distance the the measure with to easy way becomes right but harder somewhat is optimality its Proving here. Path Shortest Knight’s A others. the than heavier or lighter is it whether Heavier? or Lighter Placement Number h iceo Lights of Circle The discussed. is puzzle this of version classic Knights Alternating Four other. the for exists Walks Board Tiling Tetromino tutorial. first the in discussion conquer 2 insight. n sapwro 2. of power a is × Cutr Problem -Counters n al.Ase rttepzl’ usin o 4 a for questions puzzle’s the first Answer table. n ... = h uzecnb ovdi i steps. six in solved be can puzzle The 9 1 b2, b1, a9; , osealpsil ragmnso h counters. the of arrangements possible all see to 1 eurdpt xssfroeo h orsadde not does and boards the of one for exists path required A ocnrt ntelnetpeeremaining. piece longest the on Concentrate h uzecnb ovdb pligteged strategy greedy the applying by solved be can puzzle The h öisegBigsProblem Bridges Königsberg The h nwrt oro h usin s“yes.” is questions the of four to answer The ov h uzefor puzzle the Solve tr ysrigtenmesgiven. numbers the sorting by Start o r o se odtrietefk on just coin, fake the determine to asked not are You h ouini o h aefralvle of values all for same the not is solution The eoecrsi h he ie ftefis layout, first the of piles three the in cards Denote h akcnb copihdfrany for accomplished be can task The h rbe smnindi h divide-and- the in mentioned is problem The e h icsino ai qaeconstruction square magic of discussion the See ... iiu-oesqec srte obvious rather is sequence minimum-move A e h uoilo einsrtge hr the where strategies design on tutorial the See hr r ( are There 9 1 c2, c1, b9; , tr yaseigteqetoswhen questions the answering by Start n ... − n ov rtteisac fthe of instance the first Solve = 9adtaetealgorithm. the trace and c9 , 2) 2 2 , 3 icse ntetutorial the in discussed 3 × , × n o critical a for 4 and qae niean inside squares 3 table. 4 n ≥ 1 . n . 75 Hints odd n Cutting is useful for solving the 2 What information does a n = 1) − n Solve the problem for a small two- (2 The puzzle can be solved in 11 river Set up an equation expressing the number You might want to start by solving The formula for the sum of the first Suppose only one of the hats is black. How can There are just six integers that are not McNugget The answer to the first question is all but obvious. Use a pattern in the number of small triangles +···+ One may answer the first question affirmatively. The The first question can be answered by standard 3 After you get the main idea, try to improve on it to months in terms of the number of rabbits in some + n 1 = n Think parities. S (#30), which is a one-dimensional version of this puzzle. numbers puzzle. It might also be helpful toas the visualize apex the and triangle the with horizontal its coin right rows angle parallel to the hypotenuse. dimensional array of cards or numbers to get a crucialHats insight. of Two Colors of rabbits after previous months. Sorting Once, Sorting Twice the prisoner wearing it figureAfter this out? answering these What about questions,puzzle. the generalize other prisoners? your answers toSquaring solve a the Coin Triangle a Stick Odometer Puzzle combinatorial reasoning. With some ingenuity,be the answered without second cumbersome question computations. can Lining Up Recruits intended order was, of course,two different different; ways. it could have been executedFibonacci’s in Rabbits Problem crossings. Note that a similaron algorithm problem design is strategies. discussed in the book’s tutorial Last Ball Missing Number numbers. For the rest,decrease-and-conquer the strategy. algorithm in question canMissionaries be based and on Cannibals the make Jill’s task easy enough to perform in her head. Counting Triangles weighing of a subset of the coins provide? Cutting a Rectangular Board Exhibition Planning The answer toinvariant the idea, second which stems istechniques. from discussed a in the standard tutorial application on ofMcNugget algorithm Numbers the analysis added on each iteration.on A algorithm analysis similar techniques. example is discussedFake-Coin in the Detection tutorial with a Spring Scale 59. 58. 60. 56. 57. 55. 50. 51. 49. 52. 54. 48. 53. 47. Algorithmic Puzzles 76 63. 62. 78. 77. 76. 61. 75. 74. 73. 68. 67. 66. 65. 64. 72. 71. 70. 69. lssadMinuses and Pluses here. use to strategy appropriate Coins Up Picking move. to move from constant remains that feature some tagtToioTiling Tromino Straight numbers. Pattern a for Searching straightforward. as not is however, optimality, tour’s the Proving strategy. Rook Efficient of values Diagonal a on Checkers even Inspections Station puzzle. Gas the lead of should instance general street the same for of the algorithm instances on this located special to are you small homes few the a all Solving where tutorial. puzzle the the in used one the than Selection Site as position a possible? such as reaching quick makes algorithm What it? avoid to tries rooster Chase Rooster ycmuigtettldgtsmi l neesfo o10 to 1 from integers all in sum digit total the computing by Sum Digit goal. stated the achieve does it that prove Down Averaging eann Number Remaining time. a at bit one code the identify to used oeGuessing Code Octagons Creating parity. sum’s the explore akn el II Cells Marking obvious. are which of three solved, akn el I Cells Marking solution. a has problem the which for coins of number I Pairs into Jumping Sectors on Chips this solve to ways problem. different the three of least instance at general are there fact, In integer. positive n separately. n ol entl ep etrapoc st n ninvariant— an find to is approach better a help, definitely could tmgtb airt ov h eea ntneo h problem the of instance general the solve to easier be might It hr samc oeefiin loih o hsproblem this for algorithm efficient more much a is There o a h amrfreacpueo h ose fthe if rooster the of capture a force farmer the can How euneof sequence A notmltu a ecntutdb h greedy the by constructed be can tour optimal An hr r i ausof values six are There h nwr r ifrn o vnadodvle of values odd and even for different are answers The hn parity. Think o a s h reysrtg,btyuwl edto need will you but strategy, greedy the use may You ov h rbe o ih onsfirst. points eight for problem the Solve s h oml 1 formula the Use yai rgamn em ob h most the be to seems programming Dynamic hn parity. Think o a s akrcigt n h minimum the find to backtracking use may You h nwri ifrn o eia n binary and decimal for different is answer The o a edt osdrtecsso d and odd of cases the consider to need may You h nwri “yes.” is answer The lhuhsligtepzl o e small few a for puzzle the solving Although n i tig ihasml atr a be can pattern simple a with strings bit + n o hc h uzecno be cannot puzzle the which for 2 + ... + n = n ( n n , where + 1) / and 2 n sa is n . 77 Hints . 4 n − n 10, and 4 is six. = = n n 4 instance for a crucial insight. The nontrivial part of the question = n A simpler version of the problem is solved The puzzle can be solved by a recursive The obvious necessary condition for a tiling There is a simple algorithm for generating The answer is “yes.” board exactly once for any positive value of Think parity. . There are several algorithms that require 2 n Mark the minimum number of the board’s cells so 3 The same algorithm can make a prince to visit all The minimum number of messages for Identify a puzzle closely related to this one and use is even but not divisible by 4, no domino tiling of × Consider the The obvious necessary condition for a tiling existence > Your algorithm does not have to be optimal, but it The puzzle can be solved by a sequence of moves that n n n Tracing the algorithm by hand for, say, 1 rectangle there would contain at least one marked cell. Think blocks of successive heads and tails. × board with an equal number of horizontal and vertical tiles is n × n studying its outcome should help to answer both questions. The Prince’s Tour the squares of an Rumor Spreading II conversations for Tiling a Staircase Region existence is not quite sufficient here. Searching a Sorted Table Max-Min Weights Note that the puzzle’s statement does not requirethat the is, tour to to end be re-entrant, one move away from its startingCelebrity square. Problem Revisited in the book’s first tutorial. Heads Up Restricted Tower of Hanoi algorithm similar to the one forsecond the tutorial). classic version of this puzzle (seePancake the Sorting should definitely be more efficient than exhaustive search. Rumor spreading I Upside-Down Glasses Toads and Frogs are all but uniquely defined because thedead alternative ends. moves lead You to may obvious alsopuzzle on take the Internet. advantage of several visualizationsCounter of Exchange the the algorithm for the former to devise an algorithm forSeating the latter. Rearrangements permutations by adjacent element exchanges. Horizontal and Vertical Dominoes is to prove that if Locker Doors possible. This can be done by using an invariant. Trapezoid Tiling that any 4 is also sufficient here. Hitting a Battleship an 80. 86. 96. 94. 95. 81. 82. 84. 85. 83. 87. 88. 89. 90. 91. 79. 92. 93. Algorithmic Puzzles 78 111. 110. 109. 108. 100. 107. 106. 105. 104. 103. 102. 101. 113. 112. 99. 98. 97. aigthe making Triangle Coin a Inverting chameleons. two of meeting a after counts chameleon Chameleons The graph well-known a to of reduction half via problem. a or for recursively constructed either values be possible can ring A summations. straightforward Double- solution. a to guide Route Longest The nqeto.As oeta h nwrcnb ie ytesm formula same the by given be can answer any the for that note Also question. in Reach Knight’s A direction. right the in you point Sort of Reversal SAW. I CAT spell Counting Palindrome iterations. of number finite a Topswops of Game The osbevle of values possible Hare the and Fox The necessary. not but helpful be could string Bulb Light a on Turning Puzzle MU The help. Splitting Pile Side Other the to Jumping positive smallest their finding and solutions. equations integer some straightforward up rather a setting in by solved be fashion can it puzzle, Coconuts the solving for the methods and Monkey The Painting Room o otergtgnrlsrtg oemploy. to strategy general right the to you Removal anywhere Coin be can squares missing the board. because the so on less is correctness its of Revisited Tiling Domino hndtrieteotmlvleof value optimal the determine then n n > k Dominoes 2 hci o (1 row coin th . osdrn e ml ntne ftepzl should puzzle the of instances small few a Considering ovn e ml ntne ftepzl hudlead should puzzle the of instances small few a Solving h nwri “yes.” is answer The s h nwri “no.” is answer The . ovn h uzefrafwsalvle of values small few a for puzzle the Solving dniyasaeo h eincnann h squares the containing region the of shape a Identify netgt hne ntedfeecsbtenthe between differences the in changes Investigate o a att s reysrtg sarough a as strategy greedy a use to want may You h rttoqetoscnb nwrdby answered be can questions two first The ti airt on rttenme fwy to ways of number the first count to easier is It h o a ac h aefroehl fthe of one-half for hare the catch can fox The h nwri ys:tegm lassosafter stops always game the “yes”: is answer The ≤ h nwrt h usini ay h proof the easy; is question the to answer The hnigaottesice sbt fabit a of bits as switches the about Thinking h nwri “no.” is answer The idtebs a oivr h rageby triangle the invert to way best the Find k ≤ n k h aeo h netdtinl and triangle inverted the of base the ) . hl hr r eea ingenious several are there While n should n ’s 79 Hints k Polish the maximum number , drops. ) k k ( 3 and then generalize the H 2 has a simple but ingenious = = n n You may want to solve first the Number the boxes left to right starting Not counting the symmetric solutions, the You may use the strategy employed in the first Start by partitioning the parliamentarians into The case of (#23), which deals with checkers of just two There are a very large number of different solutions Consider the function For both versions of the puzzle, the solutions are Solve the puzzle for the maximum length of the chain is seven clips. Start by reversing the question and find the maximum is discussed. The answer to the first question can be obtained by solving , Although the puzzle can be solved in seven weighings, each 1 See the tutorial on design strategies where the simpler = k Colored Tromino Tiling tutorial to tile the same boards with uncolored trominoes. Penny Distribution Machine with a 0 and represent final distributions of pennies by bitSuper-Egg strings. Testing length of the chain for which the problem can be solved by removing National Flag Problem colors. Chain Cutting clips. For to this problem, which may allYou be can assumed find to one start atboard’s by edge the making as board’s possible. moves corner. that put the knight as close to the solution that can be extended to the general case. The Knight’s Tour Parliament Pacification two chambers in an arbitrary wayconfiguration and toward find the desired a state. way to advance the chamber Dutch National Flag Problem of floors for which the problem can be solved in Sorting 5 in 7 comparing the weights of two items, no generala sorting right algorithm approach provides for achieving this goal. Dividing a Cake Fairly solution. Note that thestraight. only restriction on lines isBachet’s that Weights they must be not difficult to guess bysolutions’ optimality applying that the is at greedy the approach. heart of It this puzzle. isBye proving Counting the empty cell can be in one ofto two two final board locations locations; of each the of remaining the peg. two may lead Six Knights Guarini’s Puzzle a simple equation; the answeranswer to to the first. the second can be extractedOne-Dimensional Solitaire from the Crossing Dots 124. 120. 121. 119. 127. 122. 123. 125. 126. 115. 116. 118. 117. 114. Algorithmic Puzzles 80 141. 131. 130. 129. 128. 135. 134. 133. 132. 142. 140. 139. 138. 137. 136. J Problem Josephus The queens. the of placement greedy a uzebfr sflptencnb setie.I atclr h solution the particular, In for ascertained. be can pattern useful a before puzzle Puzzle Counter Tait’s weeks. 5 entire the need don’t you fact, In constraints given. the under goal the achieve to enough efficient algorithms devise Wine Poisoned book). this in techniques the Puzzle decrease-and- Reve’s the apply to want may you strategy. case conquer general the for but helps, Switches Security ifrn Pairings Different Coloring Point respectively. 5, and 3, 4, are spaceships and oscillators, Life of Game The solve. to how know already Army Solitaire here. The obvious from far is instance smaller a algorithm, to decrease-and-conquer reduction a the by but instances. solved larger be can to instance solutions general the The of components important contain does ifrn eaneso h iiinof division the of remainders different hc stemnmmneeded. minimum the is which Coins Twelve and h ubro nm ar etdnx oec te stemonovariant. the The as other each to next seated pairs enemy of number the Table Round Arthur’s King have. can child a pieces candy of number smallest ad Sharing Candy required. algorithm an design and posed question II 1. time Pairs at into starting Jumping questions ask only can you but 0 location at starts spy Spy a Catching circumference. a on points equidistant placing by or table ( n :oefreven for one ): n oe fHanoi of Tower n n = o 6 mod Qen rbe Revisited Problem -Queens a eepcal ilaig hra h ouinfor solution the whereas misleading, especially be can 3 = r adrta h tesadrqiea dutetof adjustment an require and others the than harder are 3 hsdfcl rbe a esle ntreweighings, three in solved be can problem difficult This s h prahsmlrt h n tlzdt solve to utilized one the to similar approach the Use ov ipe rbe rt ups o nwta the that know you suppose first: problem simpler a Solve bev hthpeswt h ags ubradthe and number largest the with happens what Observe pl h eraeadcnurstrategy. decrease-and-conquer the Apply h nwri ys obt usin;tets sto is task the questions; both to “yes” is answer The n sadteohrfrodd for other the and ’s ovn e ml ntne ftepolmdefinitely problem the of instances small few a Solving n a ov h rbe ihrb sn 2 a using by either problem the solve can One uze(e,eg,tettra nagrtmanalysis algorithm on tutorial the e.g., (see, puzzle h iiu ubr flv el o tl lifes, still for cells live of numbers minimum The aeavnaeo h ntne ftepzl you puzzle the of instances the of advantage Take hnigbcwr a epbt oase the answer to both help can backward Thinking o ilne oslesvrlisacso the of instances several solve to need will You e ptorcrecsfrtesrio’ position survivor’s the for recurrences two up Set s h trtv mrvmn taeywith strategy improvement iterative the Use n osdrsprtl i ae of cases six separately Consider y6 h ae of cases The 6. by n ’s. n o 6 mod n = = × 4 2 n 81 Hints 1 = n Prove that this number is both . n consider first the case when the target is , n Such an algorithm does exist. Assuming the The game can be won by using a standard The answer is 4 board is 9. Find an invariant that implies that the task is Use the sum of the hat numbers each mathematician First, show that the algorithm creates a loop of coin × The game’s objective can be achieved only for Tiling the board with dominoes in a certain way may Find an invariant that implies that it is impossible to do for any . 2 = 2. n > and at some even-numbered spot. Hats with Numbers observes. One Coin for Freedom computing operation on bit strings. Pebble Spreading partitions in which the pilessize. Then, are trace formed trajectories in of nonincreasing eachloop may coin order contain in of just such one their partition a for loop a to show of that coins. the Bulgarian Solitaire sufficient and necessary for infecting the entire board. Killing Squares help to find a solution. Thebe minimum removed number from a of 4 toothpicks that need to The Fifteen Puzzle impossible for the given configuration. Hitting a Moving Target hiding spots are numbered 1 to n Infected Chessboard 147. 148. 149. 150. 144. 145. 146. 143. 4Solutions

The authors of the quotes in the epigraph puzzle in their given order are William Poundstone, George Pólya, Martin Gardner, Carl Friedrich Gauss, and Fibonacci.

1. A Wolf, a Goat, and a Cabbage

Solution Let M, w, g, and c stand for the man (with the boat, which is always on the same bank of the river as the man), wolf, goat, and cabbage head, respectively. Figure 4.1 depicts two sequences of trips that solve the problem.

Comments Most puzzles do not lend themselves to such simple solutions. This one is a rare exception in that the man has just one meaningful choice on all but the third trip The puzzle can also be solved by using the state-space graph (see [Lev06, Section 6.6]), similar to the solution of the Two Jealous Husbands puzzle in the tutorial on general design strategies. The states of the puzzle can also be represented by vertices of a cube (see, e.g., [Ste09, p. 256]). These alternative representations make it obvious that the seven trips is the fewest possible here. This classic puzzle was included in Alcuin’s collection—the earliest known collection of mathematical problems in Latin—which we already had a chance to mention in the first tutorial. On the appearance of this puzzle in other parts of the world, see [Ash90]. In modern times, it has become a standard feature in puzzle collections (e.g., [Bal87, p. 118]; [Kor72, Problem 11]). Surprisingly, the puzzle still attracts the attention of mathematicians and computer scientists (see [Cso08]).

82 83 Solutions 1. c g > n c w c c c g g w M w g M M M g w c g M M M M c c c g g w w puzzle. g w w right triangles for any integer w n M c g c w c Wolf-Goat-Cabbage g g w M w w w g 2 is obtained by cutting the rectangle along its diagonal M M M 2, one can make the first cut along the rectangle’s diagonal = n > c g w g n M M M M The puzzle provides a simple example of the worst-case analysis of A rectangle can be dissected into The answers are 11 and 19 gloves for parts (a) and (b), respectively. Two solutions to the c c c c c g g g w w w A dissection for a. In the worst case, before you get at least one matching pair, youb. will select In the worst case, before you get one matching pair of each color, you will In most puzzle books, a version of this problem is stated for balls of different MM 5 black gloves, 3 brown gloves, andglove 2 will gray have gloves—all to for yield the a same matching hand. pair. The Thus, next the answer is 11 gloves. select all 10 black, all 6 brown,glove will and have 2 to gray yield gloves a for matching the pair. same Thus, hand. the answer The is next 19 gray gloves. (Figure 4.2a). If Solution Comments Solution 2. Glove Selection FIGURE 4.1 3. Rectangle Dissection an algorithm efficiency. colors (e.g., [Gar78, pp. 4–5]). Thewas glove used version, in [Mos01, which Problem adds 18]. an extra twist to it, Algorithmic Puzzles 84 edt emade.) be to need rppoeuei eetdtettlo 5tms h rbe ilb ovdafter solved of be instance will general the problem for the course, (Of times, trips. 25 100 four- of of this total total if the Thus, the problem 1. repeated the ferried—by is reduce be procedure trips to trip four soldiers of These number boat. the the by returns stays size—measured and boy side other other the the to boat while the takes there soldier a Then boat. the with returns them n)adcnursrtg fagrtmdsg;ti taeyi icse nthe in discussed is strategy tutorial. this first book’s design; algorithm of strategy one)-and-conquer Soldiers Ferrying 4. even simpler the as to interpreted case be odd case. can the solution transferring example: second transform-and-conquer The a up). bottom applied strategy by-one utn ln h egtot t yoeue neapei hw nFgr 4.2b. Figure in by shown obtained is is example An triangles hypotenuse. right its onto two height into the triangle along cutting right a of dissection The triangles. n IUE4.2 FIGURE with up it follow and Comments Solution Comments h etnl)adte u aho hmaogtercagesdaoa notwo into diagonal rectangle’s the If along 4.2c). them (Figure of triangles each right cut then and rectangle) the etnl into rectangle mle rage ytepeiu ehdadte u n ftetinlsaogthe 4.2d). along (Figure triangles the hypotenuse of its any onto cut height then and method previous the by triangles smaller = ecnas ov h uzeb rtcnieigtecs feven of case the considering first by puzzle the solve also can We n (b) and 2 (a) etnl iscinit ih rage.Rslso h rtmto o (a) for method first the of Results triangles. right into dissection Rectangle is,tetoby aeteba oteohrsd,atrwihoeof one which after side, other the to boat the take boys two the First, n hses uzepoie odilsrto ftedces (by decrease the of illustration good a provides puzzle easy This (decrease- approach incremental the on based is solution first The n = / mle etnls(.. by (e.g., rectangles smaller 2 .Rslso h eodmto o (c) for method second the of Results 7. n − uso n fteaalbergttinlsit w right two into triangles right available the of any of cuts 2 (b) n sod efis isc h etnl no( into rectangle the dissect first we odd, is n / (c) 2 − usprle otebs of base the to parallel cuts 1 n = n (d) and 6 n odes 4 soldiers, (d) n = n n 7. u the cut : rp will trips n − 1) 85 Solutions 1 9 puzzle. 1313 1515 3 7 5 1111 2 6 1010 1414 8 4 1212 1616 Row and Column Exchanges 4 8 1616 1212 3 7 1515 1111 in 1913 (see also [Dud67, Problem 450]); it was also included in 2 6 1010 1414 The puzzle provides a good example of an invariant that is different She will stop on her first finger. The answer is “no.” The initial and target tables for the 1 5 9 1313 It is easy to see that the counting falls on the same finger every eighth number Here is how the finger count starts: Row exchanges preserve the numbers in rows, and column exchanges preserve The puzzle is quite old and well-known. Henry E. Dudeney published it in the The puzzle is similar to Problem 713 in A. Spivak’s collection [Spi02]. finger thumb first middle ring little ring middle first countcount 1count 9count 17 2 25 10 18 3 26 11 19 27 4 12 20 13 28 5 21 14 29 6 22 30 15 23 7 31 16 24 8 32 called. Therefore to answer theof question, the all division one of 1000 needsreaches by is 1000, 8, to she which find will is be the equal onsame remainder to her one she 0. first will finger This be (moving on implies while from that calling the any when middle number the divisible finger), girl by the 8. the numbers in columns. This isexample, not 5 the and case 6 for are the in tables thethe given same target row (Figure table. in 4.3): the for initial table but in the different rows in 5. Row and Column Exchanges Strand Magazine a Russian puzzle collection [Ign78, Problem 43], which was first published in 1908. Solution Comments FIGURE 4.3 Solution 6. Predicting a Finger Count from the more common parity and coloring. Algorithmic Puzzles 86 hc h beti odtrieteotu fagvnagrtm(ee h finger the 1000). (here, number algorithm the (here, given input a specified of a for output procedure) the count determine to is object the which orpol,rsetvl.Tearw niaetecosn ietos(laswt the with (always directions crossing the indicate arrows flashlight). The respectively. people, four Solution Comments h ahih srtre ytefsetpro nbt aktis h ats person fastest the trips, back If both time. on of person amount fastest minimum the a by in returned side is other flashlight the the to get to trips people one-person four two and for trips needed two-person people are three the Thus all side. not, other if the flashlight, on the already return are cross to to has have person one persons and two together solution bridge optimal the an in that proved) formally be can (and trip. second the after it returns 1 trip person first while the side after other flashlight the the to returns 2 person solution, alternative obvious the In 4.4 FIGURE .Big rsiga Night at Crossing Bridge 7. Gr6 rbe .1.Asmlrpolmwsicue nHnyDudeney’s Henry in included was problem similar collection A 3.11]. Problem [Gar06, h uzei rmMri Gardner’s Martin from is puzzle The culy 7mntsi h iiu muto ienee ee ti obvious is It here. needed time of amount minimum the is minutes 17 Actually, 3 uze uiu Problems Curious & Puzzles 536 ouint the to Solution h euneo oe ovn h uzei hw nFgr 4.4. Figure in shown is puzzle the solving moves of sequence The h uzeblnst ahrrr yeo loihi uze in puzzles algorithmic of type rare rather a to belongs puzzle The 1,2,5, 5, 5, rdeCosn tNight at Crossing Bridge 1 1 1 1 0 0 0 1 5, 1,2 1,2 0min 10 min 1 min 2 min min 2 min min 2 min min 1 min 0 ooslBo fSotPzlsadProblems and Puzzles Short of Book Colossal Dd7 rbe 164]. Problem [Dud67, 1 2 uze aes1 ,5 0rpeetthe represent 10 5, 2, 1, labels puzzle: 1,2,5, 5, 5, 2 2 1 1 0 0 1 0 87 Solutions k 3 minutes, people need = n 1 irrespective of an + 18, and so on. So, k , became a hot topic + − 14 minutes because at least 18, 2 = + 2 + 2 19, 2 + + puzzle (see the second tutorial). 45 such pairs (we subtracted the number of Bridge and Torch Problem = 2 / 19 minutes. If one of the two back trips is not done by 10) = − 2 (p. 169); it was later included in [Ave00, Problem 9.22]. 10 + · 1) + The solution is based on the same invariant idea that underlines the As discussed in the first tutorial, the puzzle cannot be solved correctly Breaking a Chocolate Bar (5 The sum is equal to 1000. The answer is 499 moves. + 1) + The object is to compute (in one’s head) the sum ofThe the first method numbers is in based the on table the observation that the sum of any two numbers Any move decreases the number of remaining sections by 1. Therefore, after Submitted by Leo Moser, the puzzle was published in the January 1953 issue of This puzzle, also known as the and trips to the other side will be at least 10 one pair will have to include the slowestthe person bridge and whereas hence the take other 10 two minutes pairs tototal will cross crossing take time at will least have 2 to minutes take each. at Hence, least the 17 minutes. since there are (10 9. Mental Arithmetic Mathematics Magazine the fastest person, then the return crossing times will be at least 2 shown in Figure 4.5. in the squares symmetric withand respect upper to right the corners diagonal is connecting equal the to lower 20: left 1 moves, the total number of remaining sections will be 500 order in which the sections arethe assembled. entire Hence puzzle 499 is assembled. moves will be made before the squares on that diagonal from the total number of the squares), the sum of the Solution Comments Solution Comments will have to participate in(10 each pair going to the other side, for the total time of 8. Jigsaw Puzzle Assembly to cross a bridgeindividual under crossing the times. The same proof constraintsby of Günter this as Rote algorithm’s described in optimality 2002 above was [Rot02].website published and For [Sni02] further and arbitrary the extensions, paper see by Moshe Roland Sniedovich’s Backhouse [Bac08]. better known by the straightforward application ofthe the reasons greedy many people approach. find This it harder might than be it appears one at of the first glance. on the Internet some years ago; itbook has as also one of been the included Microsoft in interview William puzzlespage Poundstone’s [Pou03, p. [Sillke] 86]. Torsten contains Sillke’s some web interestingthe material earliest related reference to to the this problemand puzzle, in an including the algorithm for book the by general Levmore instance and of Cook the [Lev81] problem, in which Algorithmic Puzzles 88 h ae ti h hr oni h ihe ru hti ae fte ontweigh not do they if fake; is that group lighter the weigh in they coin If third scale. the the of is cups it opposite the same, coins. on first the lighter them the three put and the If them among fake. of is two fake lighter any lighter Take the the balance, identify other a the will yield among coins not is does two fake weighing these the same, weighing the and weigh coins, they If two scale. the of cups opposite the 0 aeAogEgtCoins Eight Among Fake A 10. [Cra07]. book one. to simpler solution the to second sums the the in reducing twice with along formula extremely problem this is the used itself We formula analysis. the algorithm that in algorithm there useful on tutorial mentioned the also in We described as techniques. integers, analysis hundred first the of sum the find (55 20 to equal is diagonal that outside numbers 4.5 FIGURE Solution Comments 55 h ignl h oa u seult 900 to equal is sum total the diagonal, the y1ta hi oneprsi h o bv.Tesm stu o l h other the all for true 55 is to same equal is The sum above. total the row Hence well. the as in rows counterparts their than 1 by u ntefis o,a icse ntescn uoil seult 10 to equal is tutorial, second the in discussed as row, first the in sum h u ftenmesi eodrwi 55 is row second in numbers the of sum The eetfo h ie on w ruso he on ahadptte on them put and each coins three of groups two coins given the from Select h rbe ssmlrt usin13 nteWl tetitriwquestion interview Street Wall the in 1.33 Question to similar is problem The h eodmto optstesmrwb o o ounb oun.The column). by column (or row by row sum the computes method second The · + 10 90) + 10 = al fnmest esme pi the in up summed be to numbers of Table h nwri w weighings. two is answer The · 55 h rtmto sstesm rc alGuspeual sdto used presumably Gauss Carl trick same the uses method first The 45 · 10 10 9 3 2 1 = . . . + 1000. 10 11 3 9 2 (10 11 10 + 9 3 20 11 10 +···+ 9 11 10 9 90) ... 11 10 ... + 9 + 100 = · 0sneec ftenmesi larger is numbers the of each since 10 10 11 + 45 9 55 = (55 = etlArithmetic Mental · 10 17 11 10 1000. 9 0.Wt 10 With 900. + + 10 10) 17 11 18 9 10 + · 18 17 11 10 19 (1 . . . (55 + 2 + · puzzle. +···+ 10 · 20) 11 = / +···+ 2 0 on 100 = 9) 55. = 89 Solutions Twelve Coins CEH, B is the fake; (e.g., [Lev06, Section = FGH, only A, B, and C may FGH (the first weighing results [Ave00, Problem 9.11]. < = CEH, C is the fake. The case of decision trees > [Gar88a, p. 26] and Averbach and Chein’s and halving the problem size does usually yield 55 genuine coins, indicates the number of the fake 3 2 = = Scientific American 10) The solution is based on the representation change idea. Since 8 The puzzle can be solved in one weighing. +···+ CEH, A is the fake; and if ADF 2 FGH is symmetric to the case just discussed. < + > The problem has an alternative solution in which the second weighing does not Number the coin stacks from 1 to 10. Take 1 coin from the first stack, 2 coins The puzzle has an obvious generalization to an arbitrary number of coins, The puzzle was included, among others, in the first collection of Martin According to T. H. O’Beirne [Obe65, p. 20], the puzzle dates from the depend on the results ofE, the F, first G, one. H. Label Onweighing, the the weigh first coins A, D, weighing, by F weigh the against A, C, letters E, B, A, H. C If B, against ABC C, F, D, G, H. On the second extremely efficient algorithms, it isthe quite problem understandable in why three weighings many instead people ofa solve two. situation This, when however, a is a decrease rarehighlights by a example a dilemma of of factor dealing larger with than problemsSometimes stated 2 it with is specific is possible. numerical possible data. The to puzzlegiven while take also in advantage others (as of here) one some can special be misled property by it. of the data ABC in a balance), all theseis six equivalent coins to are genuine, weighing and D therefore against the E. second If weighing ABC still be fake. Therefore if on the second weighing ADF Gardner’s columns in Problem Solving Through Recreational Mathematics from the second, and so on,all until these all 10 coins coins together. are The takenof difference from between the (1 last this stack. weight Weigh and 550, the weight although the optimality proof of theby division-into-thirds algorithm using is more usually done advanced techniques such as if ADF coins weighted, which is equal toexample, the if number the of selected the coins stack weigh with 553third the grams, stack fake that 3 coins. contains coins For the are fake fake coins. and hence it is the Comments Solution Comments the same, the lighter oneweighing, is the the above algorithm fake. requiring Since just two the weighings problem is optimal. cannot be solved in one 11. A Stack of Fake Coins First World War.United Nowadays, States. it For is a much often harder offered coin weighing during problem, job see interviews the in the 11.2]). puzzle (#142). Algorithmic Puzzles 90 egbrn ubr;i nitreto a utoeo uhnihos tgt the gets the it neighbor. of neighbors, the of sum such that of the as one as number just same computed intersection has is an intersection number If an its row. if neighbors, numbers; each neighboring upper within and right left to the left both and has row by numbers row these A, computed area intersection fenced-off be to 1 the can of outside assignment grid the with the Starting in 4.7). Figure of intersection (see number every the to finds A approach from This paths tutorial. shortest first the in discussed strategies design 2 a form dominoes option two only no the that is assumption which shown 13, the tiling tile contradicts below available, a horizontally with domino up a end Placing we 4.6. further, Figure in logic same hor- the a by applying covered By be domino, must domino. vertical row izontal that a of by column covered second is the be in must square square the the top therefore in the left and square from the row upper Then second its the 4.6. of Figure that column in first 1 assume numbered may domino horizontal we a by symmetry, covered board’s the of Because einsrtge.Cutn ah sawl-nw plctoso dynamic of applications well-known a is paths Counting strategies. design Paths Blocked 13. tutorial. second the in discussed idea invariant the of version some on IUE4.6 FIGURE Solution Tiling Questionable 12. Comments Solution Comments h ais a ogti st pl yai rgamn—n ftealgorithm the of programming—one dynamic apply to is it get to way easiest The exist. does tiling a such that Assume contradiction. by proved be can This h uzei rbe 0 n[o9,p 74]. p. [Fom96, in 102 Problem is puzzle The ouint the to Solution h nwri 7paths. 17 is answer The exist. not does tiling requested A iia rbe a icse ntebo’ uoilo algorithm on tutorial book’s the in discussed was problem similar A based not is that proof nonexistence a of example rare rather a is This 1 2 4 3 usinbeTiling Questionable 6 5 7 8 10 9 puzzle. 12 11 13 × square. 2 91 Solutions B 5 1 5 9 1717 2 rectangles, and nine × 2 part colored the same color, 4 1 4 4 8 × 1or1 × 3 1 3 4 1 squares, twelve 1 × 2 1 2 3 4 2 rectangles at the board’s border by 180 degrees and × 1 1 1 1 1 A 2 squares by 90 degrees. 2 3 4 1 × The answer is 25 pieces. Optimal cutting of the board to reassemble into a chessboard. Counting shortest paths from A to B with a fenced-off area shown in gray. 4 region of the board given has to be cut both horizontally and vertically. × 2 squares each colored as in the standard chessboard. The standard chessboard Since the standard chessboard has no 2 × each 4 Four horizontal and four vertical cuts shown inpieces, Figure which 4.8 is dissect the minimum: the four board 1 into 25 2 can be assembled from the piecescan obtained simply in rotate a eight variety 1 of ways. For example, one rotate four 2 FIGURE 4.8 Solution 14. Chessboard Reassembly programming (see, e.g.,programming [Gar78, are usually less pp. straightforward. 9–11]). Other applications of dynamic FIGURE 4.7 Algorithmic Puzzles 92 npcino t mletisac.(h mletisac sa xeto here: exception an is instance smallest (The 3 instance. all smallest its of inspection IUE4.9 FIGURE Solution Comments Comments FIGURE as n aho hmlae omol o n oergttoio(iue4.9). (Figure tromino right different more three one in for only tiled room be a can leaves one, them left of each lower and the ways, say, board, the of corner a Indeed, otetidpolmcnb osdrdadvd-n-oqe application. solution divide-and-conquer the a Finally, considered idea. be invariant can problem the third on the based to is question second the to answer h oe etcorner. left lower the etnlst ieec fte ihtotoios(e iue41 o nexample). an for 4.10 Figure (see trominoes two with them of each tile to rectangles [Par95]. sntdvsbeb 3. by divisible not is 5 rmn Tilings Tromino 15. 31]. p. [Gra05, .Tease s“o eas h oa ubro qae nay5 any in squares of number total the because “no” is answer The b. .Tease s“o eas 3 a because “no” is answer The a. h uzei iia oPolm5 nInParberry’s Ian in 50 Problem to similar is puzzle The .Adsrdtln a eesl bandb iiigtebadit 2 into board the dividing by obtained easily be can tiling desired A c. n × 4.10 3 n he ast tr iiga3 a tiling start to ways Three h nwri n”frprs()ad()ad“e”frpr (c). part for “yes” and (b) and (a) parts for “no” is answer The orswhere boards iiga6 a Tiling h uzei rmSri Grabarchuk’s Serhiy from is puzzle The h nwrt h rtqeto sotie yteexhaustive the by obtained is question first the to answer The × or ihtrominoes. with board 6 n > a etldwt rmne Mr6 .3])The 31].) p. [Mar96, trominoes with tiled be can 1 × or antb ie ihrgttrominoes. right with tiled be cannot board 3 × or ypaigargttoiocovering tromino right a placing by board 3 h e uzeClassics Puzzle New The rbeso Algorithms on Problems n × 5 n board × 3 93 Solutions 3, 1) = + 1 and n n 3). The > (2 n = 1, it cannot × n > 1) n + 1. n = n moves it will always be sides to be fried and any n is odd and greater than 3, 1, the king can only reach n n minutes for every = n minutes to do the job. This is n n 1 and 8 for .If 2 > 1) n 1 moves, the king can reach those and + for > pancakes have 2 n 2 n n 1) + n squares. 2 1) + n respectively. Consider the farthest squares the king can reach 3 pancakes, which is even, as indicated above. , 1. 1, the above algorithm requires n − = > n The above algorithm can be considered a decrease-by-two algo- n n a. The answer is (2 The minimum amount of time needed is 1, then 2 minutes are needed to fry the pancake on both sides. If is even, the solution is obvious: for every pair of pancakes, fry them both = n n moves. These squares form a border: all the squares on this border and all n b. The answer is ( For every If the king moves only horizontally or vertically, after If If In one move, the king can reach any of the eight squares adjacent to the starting The earliest reference to this puzzle in ’s bibliography [Sin10, on a square of thean same even and or odd opposite color to the color of its starting square for 2 minutes for the minimum time possible because number of such squares is equal to (2 return to the starting square. simultaneously, first on one side and then on the other. one. After two moves, it can beleaving at and any then of the returning following: there), the anyfirst starting square of to (by the a first 8 neighboring squares square adjacent and16 then to squares forming reaching it the the (by middle target moving square square), shownThus, and by all connected any points the of in the squares Figure reachable 4.11a. square in or two within moves it. are In either general, on after the perimeter of this algorithm can fry no more than two sides in 1 minute. only those squares that are within or on the perimeter of the (2 one can do the job in 3Then minutes fry as pancake follows. First, 1 fry on pancakesFinally, the 1 fry and both second 2 pancakes side 2 on and one together 3 side. with on the pancake second side. 3 If on its first side. square with the center at the starting square (see Figure 4.11a for eight squares adjacent to its starting square but, unlike the case of in Solution Comments 16. Making Pancakes Solution an optimal algorithm can fry the firstthe three remaining pancakes as just described and then fry 17. A King’s Reach rithm; but the keypancakes. to the puzzle is, of course, theSection optimal 5.W], way is frying dated 1943, ofSince although then, three it he was says included in that a variety it ofp. puzzle is 9, books probably Problem (e.g., [Gar61, 38]). older p. 96]; than [Bos07, that. Algorithmic Puzzles 94 iue41bfra lutain)Teeae( are There illustration.) an for 4.11b Figure h poieclr u h qae ftelwrlf n pe ih onr fthe impossible. question of of in corners journey squares right the on upper making and end same, left the and lower colored start are the to board of squares have moves; the will 63 But journey make color. to a opposite need such the would odd, it is once, number board this the of since squares the all visit To color. nain da oeta h rbe ffidn ngtstu hog l the all through tour knight’s 8 a standard finding a of of problem squares the that Note idea. invariant Journey Corner-to-Corner A 18. of subject the is knight chess the the for question same The induction. mathematical Solution Comments FIGURE in king the by reachable are it within color same the of squares the n Solution Comments qae.()Rahbesursi he oiotladvria oe wiecircles) square). (white starting the moves plus circles vertical (black and moves vertical horizontal and horizontal three four in in and squares Reachable (b) square). bo ae) h rtnn ubr r n-ii,therefore one-digit, are numbers nine first The pages). (book 9 aeNumbering Page 19. diagonally at end and board. start the to of required corners not opposite is tour the if solutions have does (#127), ≤ h qae hr h ngtsat n nsismv r laso h opposite the of always are move its ends and starts knight the where squares The Let ngtsReach Knight’s .Tenx 0nmesfo 0t 9 nlsv,aetodgt.Hence, two-digits. are inclusive, 99, to 10 from numbers 90 next The 9. D 4.11 ( n etettlnme fdcmldgt ntefirst the in digits decimal of number total the be ) h ore nqeto simpossible. is question in journey The h nwri 6 pages. 562 is answer The a ecal qae ntresadr igmvs(lstestarting the (plus moves king standard three in squares Reachable (a) h uzei tnadeecs xliigsur ooiga the as coloring square exploiting exercise standard a is puzzle The by rigorously more proved be can solutions the of correctness The (a) uze(10 ae ntebook. the in later (#100) puzzle D ( n ) × = hsbad nw sthe as known chessboard, 8 9 + 2( n − )fr10 for 9) n + 1) 2 ≤ fsc squares. such of n ≤ 99 ngtsTour Knight’s (b) . D n ( oiieintegers positive n ) n = oe (see moves n problem o 1 for ≤ 95 Solutions 1919 Maximum Sum 1313 . 6 2222 999 2 ≤ 1111 (b)(b) n . 189, which means that some 7 ≤ 1717 = 1578 1010 = (99) 1111 D 99) 99) for 100 − − n 6 n 3( 3( + 7 + 189 4 9 ) for this range is 189 n ( = D 2 4 ) (a)(a) n ( 562. D 6 5 = The puzzle is from the Project Euler website [ProjEuler]. The puzzle is included in the book as an example of a simple n Illustration of the dynamic programming algorithm for the 3 Using the standard dynamic programming technique, discussed in the 4.12 puzzle. (a) Input triangle. (b) Triangle of maximum sums along descending paths 1 Figure 4.12 illustrates the algorithm for the triangle given in the problem’s Similar questions have been a common feature in elementary recreational three-digit numbers are needed to reachpuzzle. the There total are digit 900 three-digit count decimals, of which 1578 leads given to in the formula the Descent with 22 being the largest. Comments FIGURE Solution Its solution is Comments To answer the puzzle’s question, we need to solve the equation The maximal value of 20. Maximum Sum Descent algorithm analysis. mathematics books. first tutorial, compute the maximumto sum each along number a in descending the triangle. path Startequal from with to the the the apex, apex number for itself. which Then this computeto the sum right sums is across moving the obviously triangle’s top rows down as and, follows. For say, anythe left number last that in is its either row, the first add or the sumpreceding previously row computed and for the the number adjacent itself; number for in any the last number that in is its neither row, the add first the nor larger the numbers of the in previously computed the sums for preceding thecomputed two row for adjacent the and numbers at the the base number of the itself. triangle, find When the all largest amongstatement. such them. sums are Algorithmic Puzzles 96 mle qae,i sovosta h rbe a oslto o hs he values three these for solution no has of problem the that obvious is it squares, smaller FIGURE Solution Dissection Square 21. FIGURE hsslto for solution this ouincnb eeaie oayeven any to generalized be can solution ecnfis isc h ie qaeit 2( into square given the dissect first can we for .Ti ouini lutae nFgr .4for by 4.14 squares Figure obtained into in the corner) illustrated of is left number solution top total This the 3. the in increase one will which the ones, (e.g., smaller squares four obtained the of any dissect then ln w daetsdso h ie qae ihtesd egho ahsmaller each of length side the with 1 square, equal given square the of sides adjacent two along If osdrn h atta h orrgtage ftegvnsur utb in be must square given the of angles right four the that fact the Considering n n tde aeoeovosslto for solution obvious one have does It . n = > 4.13 4.14 2 , n d,ta is, that odd, and 5 3 qaecnb isce into dissected be can square A , qaedseto nonn squares. nine into dissection Square squares. six (b) and squares, four (a) into dissection Square n 5. and / k n ho h ielnt ftegvnsur.Fgr .3 illustrates 4.13b Figure square. given the of length side the of th = (a) 6. n = 2 k + where 1 n n k = mle qae o every for squares smaller − n 2 k n = k )sursa ecie bv and above described as squares 1) > = yhvn 2 having by ,soni iue41a This 4.13a. Figure in shown 4, ,then 2, 9. (b) n = k 2( − k qa squares equal 1 − n 1) > + except 1 3 , and 97 Solutions the , one , 1 = n ’s separately and 1 teams to insert n − n Dutch National Flag Problem into the list right before the first team n ,... , 3 , 1, solve the problem recursively for an arbitrarily chosen > n The above algorithm is similar to the principal part of The algorithm is a perfect illustration of the decrease-and-conquer Here, we considered the cases of even and odd 1 teams. Then scan the obtained list of these Here is one of the algorithms to solve the puzzle. Find the leftmost The following recursive algorithm solves the puzzle. If − n As far as the puzzle’s origins are concerned, it has been known for a long time. The puzzle is a simplified version of the Figure 4.15 illustrates the algorithm. The puzzle has been included in several books (e.g., [Sch04, pp. 9–11]). The group of 23. Polish National Flag Problem For example, its version for chesswas tournaments mentioned in (a E. chess Gik’s game book [Gik76, can p. end 179]. with a tie) on the list that lost to itteam in not the yet tournament. on If the there list lost isat all no the its end such of games team—that the to is, list. the if teams the on the list—insert that team problem is solved. If the team not included in theto group it right in before the the tournament. firstthe If team list on there lost the is list all no that its suchthe lost games team—that list. to is, the if teams the on team the not list—insert yet that on team at the end of of the most important sortingconsidered algorithms a decrease-and-conquer (e.g., algorithm [Lev06, in Sectioncan which vary 4.2]). an from It one instance iteration can size to be another. decrease puzzle (#123) given later in the book. Comments Solution Comments Solution Comments strategy. It can also besome implemented bottom ordering up (incrementally) of bysuccessively the starting inserting with teams, teams 2 initializing a list with the first team, and then 22. Team Ordering solved the more difficult of the twoone (the (the even odd case). case) by transforming it to the easier related problem of dissectingharder, a of course—see square [Ste04, into Chapterand squares pertinent 13], results. for of a different good sizes exposition of is its much history white checker and the rightmost red checker. Ifright the of leftmost the white rightmost checker is red to checker, the repeat the the problem operation. is solved; if not, swap the two and Algorithmic Puzzles 98 n igcnb nepee sbsdo h reysrtg.A oterook’s the to As strategy. greedy the on based a yields as it interpreted coloring, be can king and Solution Colorings Chessboard 24. FIGURE Comments qae,a least at squares, etcly rdaoal,a es orclr r eddt oo ah2 each color to needed are colors four least at diagonally, or vertically, ntoopst oospoie ooigrqie yteqeto.I soefor one is It question. the by board required the coloring of a n coloring provides standard colors the opposite and two needed, in obviously is color one than more rpigteclr htfl usd h or oclrtesursi h leftmost the in squares the color for to example board An columns. the first outside the fall say, that color, colors to the is wrapping same, the colored are in in line coloring same row a the get in to squares two way no easiest that The sufficient. also but necessary only oesursotietebad n ooigec 2 each coloring and board) the outside squares some h qaeo h andaoa.Tu,tease o h ihpis as bishop color the same for the answer column the same Thus, diagonal. the main in the squares on the coloring square all this the color extend to to is way board easiest entire The the corner. to right lower the to corner left upper least four. is king the for answer the that implies scheme coloring same the using ftebad iiigtebadit uhdson ein sm fwihmay 4 which parts of as of (some thought regions be can disjoint that such rectangles into smaller to board degenerate the Dividing board. the of ngt ihp n igaees,i snttecs o h ue se[Iye66]). (see queen the for case the the not for is coloring it minimal easy, are the king about and questions bishop, the knight, exactly while and And row each column. in each once in exactly occurs once symbol each that way a such in symbols = .Snetebso hetn l h qae ntesm ignladn other no and diagonal same the on squares the all threatens bishop the Since b. .Snetekn hetn nyeeysur daett thorizontally, it to adjacent square every only threatens king the Since c. .Snetero nytraesaltesursi h aerwo oun at column, or row same the in squares the all threatens only rook the Since d. :n w ngt hetnec te nsc ml board. small a such on other each threaten knights two no 2: n oosaenee oclreeyln rwo oun.Ti ubri not is number This column). or (row line every color to needed are colors n 4.15 oosadte hf h ooigshm n ount h ih with right the to column one scheme coloring the shift then and colors .Frtekih,temnmmnme fclr for colors of number minimum the knight, the For a. lutaino h loih o the for algorithm the of Illustration h tagtowr ouin ie bv o h ngt bishop, knight, the for above given solutions straightforward The n oosaenee oclrtemi ignlo h or rmits from board the of diagonal main the color to needed are colors ai square Latin n = sgvni iue4.16. Figure in given is 5 forder of n :an oihNtoa lgProblem Flag National Polish n × n × al le with filled table einwt orcolors four with region 2 × n ein with regions 4 n . > × n . n oosso colors stwo: is 2 different region 2 99 Solutions intervals n th interval i 1 puzzle. 2 3 5 4 3 2 1 are the dates of birth and death 2 i d 4 3 2 1 5 , i Best Time To Be Alive b 3 th interval. If several intervals have the j )—find an interval that is an intersection 3 2 1 5 4 n , the closing parenthesis of the 4 j b ≤ i SolutionSolution = i ≤ 2 1 5 4 3 d 3 5 board in five colors with no two squares in the same row 2 1 5 4 3 2 × ) —where in our case n 1 d , n b ( Representing the input data as intervals on the real line is an 2 Illustration of the algorithm for the Coloring a 5 In general terms, the problem can be stated as follows. Given ,... , 4.17 4.16 th person in the index (1 ) 1 (( )( ) ())() (()(( i 1 d , It is helpful to visualize the intervals depicted on the real line, as it is done in 1 b of the largest number of thenot include intervals their given. end All points. the If intervals are open, that is, do of the or column colored the same color. Comments FIGURE 25. The Best Time To Be Alive Solution FIGURE precedes the opening parenthesis ofsame the opening parenthesis, itcourse, should the same be is true counted for a for coinciding closing each parenthesis. of theseFigure intervals; 4.17. of The sequence of thesolution interval to parenthesis the holds problem. the It key is toright not an while difficult efficient increasing to the see parenthesis that count by scanning 1decreasing the on sequence it every left by opening to parenthesis 1 and on everymaximum on closing the one left solves parenthesis of the the problem:simply desired the the interval, next whose count one. right reaches parenthesis its is example of the representation changethe variety strategies of outlined in transform-and-conquer—one the of first tutorial. ( Algorithmic Puzzles 100 lhbtclyodrdls r ihro h omU form the of either are list ordered alphabetically hna5-erln erhfrapofo hscnetr,ada$-ilo prize $1-million a and conjecture, this of proof a for most more search fact, a In long Despite known. 50-year exists. not is a does graph than algorithm an arbitrary determine such an that to in believe algorithm scientists circuit the computer efficient Hamilton example, No a not. of circuits—for existence do Hamilton the Game—some have Icosian graphs the of Some graph returns vertex. then a and starting once, exactly of the vertices other existence to the of the each visits is vertex, some question at starts in problem circuit The Hamilton graphs. with dealing problems Solution Comments ∗∗ 4 Solution Rank the Find 26. Comments FIGURE hsmasta UIGwl ei oiin720 position in be will TURING that means This etr a ei n re,teeae5 are there order, any in be can letters 7 h csa Game Icosian The 27. 54–55]. pp. ranking lmnsaenmee rm1t 720. to 1 from numbered are elements UIGi h lhbtclyodrdls seult 5 following to “words” equal is of list number ordered total alphabetically the the in Thus, TURING tutorial). first the (see respectively · h oa ubro od aeu ftesxltesi qa o6 to equal is letters six the of up made words of number total The , 3 hr a where · 2 o eraeb-n loih o hspolm e,freape [Kre99, example, for see, problem, this for algorithm decrease-by-one a For . 4.18 · 1 h uzehs3 ouin,oeo hc ssoni iue4.18. Figure in shown is which of one solutions, 30 has puzzle The 598. is answer The = n ftesltost the to solutions the of One ∗ h uzepeet pca aeo n ftems intriguing most the of one of case special a presents puzzle The called problem well-known a of instance an is puzzle The tnsfroeo h i etr o led nte“od”Snethese Since “word.” the in already not letters six the of one for stands 2 setefis uoil.Te“od”floigTRN nthe in TURING following “words” The tutorial). first the (see 720 asqec fajcn cnetdb neg)vrie that vertices edge) an by (connected adjacent of sequence —a csa Game Icosian != 5 · 4 · . 3 ∗∗∗∗∗ · − 2 122 · !+ n 2 and 1 = 2 ro h omTURN form the of or != 9 ntels,i its if list, the in 598 != 120 2 + · != fthem, of 1 2 = 6 122. · 5 · 101 Solutions 0 2 1 3 9 5 1 2 5 1 8 4 1 1 in the second tutorial (b)(b) 1 3 7 1 4 6 1 0 2 1 3 5 9 The Königsberg Bridges Problem 1 2 5 1 8 4 1 1 (a)(a) (a) Graph of the figure to trace. (b) Its Euler circuit. The analysis of 1 3 7 1 4.19 number of edges for which the vertexstart is at an any endpoint)—then of a its trace vertices can where it will end. one of these odd vertices and end at the other. There is a well-known algorithm for constructing an Euler circuit. It starts at a. The first figure can be traced with the restrictions imposed: its graph • Exactly two of its vertices have odd degrees—then a trace must start at • All the vertices of the multigraph have even degrees (i.e., an even 4 6 1 an arbitrary chosen vertex and proceedseither along all previously untraversed of edges them until no are untraversed traversed edge or out the ofuntraversed. In path it the available latter returns case, while to the some obtainedthe the circuit of same is starting operation the removed vertex from is graph’s the repeated with edges graphremaining recursively and remain part starting at of a the vertexvertex graph that follows and is from the in the removed both graph’seven the connectivity circuit. degrees.) and (The Once the existence an fact Euler of thatgraph, circuit all such is it its a constructed vertices is for have “spliced” the intograph. remaining part the of first the circuit to yield an Euler circuit for the entire (Figure 4.19a) is connected and all its vertices have even degrees. FIGURE 28. Figure Tracing Solution established in year 2000unresolved. for resolving the issue one way or another, it remains implies that a figure can beover any traced line without in it lifting if and pen only off ifone the the of multigraph the paper of two the or figure conditions: going is connected back and satisfies Algorithmic Puzzles 102 etcso noddegree. odd an of vertices same the essentially using and 3 path: vertex following at the degrees get Starting even can 8. have we algorithm, vertices and its 3 all and vertices connected two: is except it 4.20a), Figure (see graph a as circuit the get we edges, “outside” ue’ hoe osbc oPtrG at(8110) rmnn Scottish prominent a (1831–1901), 232]. Tait p. [Pet09, G. physicist Peter and mathematician to back goes theorem Euler’s decrease-by-variable-number the in falls algorithm category. the unpredictably, varies hnpcig a,vre sacmo etxwt h eann ato the of part graph: the remaining of the part remaining with the for vertex circuit Euler common following a the get as we graph, 2 vertex say, picking, Then the for circuit Euler 4.19b): following (Figure the graph yields entire former the into circuit latter the “Splicing” graph: the of we part graph, remaining the the of for part circuit Euler remaining following the the with get vertex will common a as 4 vertex say, Picking, Comments for path Euler following 4.20b): (Figure the graph yields entire path the former the into circuit latter the “Splicing” .I sipsil otaetetidfiuebcueisgahhsmr hntwo than more has graph its because figure third the trace to impossible is It c. considered imposed: restrictions the with traced be can figure second The b. its following and 4.19a Figure in graph the of 1 vertex at starting example, For iuetaigi tnadpolmi uzebos hsapiainof application This books. puzzle in problem standard a is tracing Figure 8 1 − − 3 1 − 3 12 2 − − − − 4 9 − 2 ic h ieo ue iciscntutdb h bv algorithm above the by constructed circuits Euler of size the Since − 4 10 − − 11 − 7 5 − 10 − − 7 − 4 2 9 − 11 − 7 − 2 − − − 11 − 9 − 1 5 13 − 8 − 3 − − 10 − − − 13 4 9 10 − 12 4 7 − − − − − 9 − 8 8 − 12 − 9 1 10 − − 15 . − 6 − 12 11 − − − 6 15 6 − − − 2 14 − − − 11 12 2 − 3 14 − 3 − − − − 6 1 − 7 9 − 10 − 7 − − 6 − 7 . 4 − 8 5 − − 10 − − 7 3 8 − − 4 2 − − . . 3 6 4 11 − − − 4 − 3 5 − − − 12 1 10 9 . . − 103 Solutions ,is 8 , 15 · 4 1 7 4 1 = , respectively, magic sum i , 15 h · , 3 0 g ) 2 3 1 c 1 1 ; + (b)(b) f e + , 3 e e , = + d 3 magic square construction. ) 1 5 9 2 6 ; g 9 i c ( × , + b + h , ) i a + 5 + g e ( + + ) a f ( 8 9 + + e ) h + 1 7 4 + 5 1 d 15. Second, the central cell must contain 5. Indeed, ( e + + = 5. What remains is to arrange pairs (1, 9), (2, 8), (3, 7), and ) b 3 c ( = 1 / 0 2 1 3 e + 1 + 1 9) (a)(a) b ) f + + a Two possible placements of 1 and 9 in a 3 (a) Graph of the figure to trace. (b) Its Euler path. The first helpful step is to find the value of the common sum for e ( 2 6 9 + + + ··· + 4.21 4.20 e d 2 ( 3 = + Taking into account the table’s symmetries, there are only two qualitatively 5 and adding the numbers in the seconddiagonals, we row, obtain the second column, and the two main different ways to put 1corners and (see Figure hence 4.21). 9: in the table’s corners and not in the table’s (4, 6) around it. denoting the numbers in the row 1, 2, and 3 FIGURE which implies that Solution 29. Magic Square Revisited FIGURE the magic squares in question. This sum, called sometimes the equal to the sum of(1 all the numbers in its rows divided by the number of rows: Algorithmic Puzzles 104 hi pernei nin hn.Wiesvrlagrtm o osrcinof construction for algorithms order of several squares While magic China. ancient in appearance their ie nteWrdWd e eoe othem. to devoted Web Wide World numerous the and on 7]), sites Chapter chapters [Kra53, [Pic02]), (e.g., books (e.g., mathematics monographs recreational many several in check on can information more reader For the discovered. squares, been magic has order arbitrary an of squares magic l fte r ymti n a eotie rmoeo h ih yrotation by eight the of one from obtained course, be Of can reflection. 4.23. and and Figure symmetric in are shown are them 3 of order all of uniquely squares determined magic are can eight cells which remaining All 8, the afterward. and for numbers 6 The with ways. filled two be in then done must be 1 containing column) or (row line The FIGURE are alternatives symmetric These 9 5. and with 1 column put to same 4.22. ways the Figure in other or shown three row also same are the There in one. second the on concentrate we 5, than larger number have column. a last to there the able put with we be problem if not same and will the row, have we first will corner, the right in 15 upper of the sum in magic if 5 the square: than magic less a number form to a completed put be we cannot arrangements these of first the But Comments FIGURE 4 3 8 2 7 6 hs ecnaadntefis atal le al nFgr .1and 4.21 Figure in table filled partially first the abandon can we Thus, 4.22 4.23 9 9 5 5 1 1 9 5 1 orpsil oiin f1 ,ad9i 3 a in 9 and 5, 1, of positions possible Four ih ai qae fodr3. order of squares magic Eight ai qae aefsiae epefrtosnso er since years of thousands for people fascinated have squares Magic 2 7 6 4 3 8 9 9 2 4 4 9 2 n > aebe eie,n oml o h ubrof number the for formula no devised, been have 2 5 5 7 3 3 7 5 1 1 1 6 8 8 6 6 7 2 8 3 4 1 5 9 1 5 9 1 5 9 × ai square. magic 3 8 3 4 6 7 2 8 6 1 6 8 1 1 5 5 3 7 7 3 5 2 4 4 9 2 9 9 105 Solutions 2, a9; / -unit a9a9 c9c9 b8b8 a8a8 c8c8 b7b7 a7a7 c7c7 b9b9 1) n Pile 3Pile 3 ... game in − Cutting a l ( a6a6 c6c6 b5b5 a5a5 c5c5 b4b4 a4a4 c4c4 b6b6 (c)(c) = Pile 2Pile 2 2 is odd and greater / . In particular, for l l n  ≥ a3a3 c3c3 b2b2 a2a2 c2c2 b1b1 a1a1 c1c1 b3b3 2; if k / Pile 1Pile 1 l Number Guessing 2 and / 100. 1) < + b3b3 b6b6 b9b9 a3a3 a6a6 a9a9 c3c3 c6c6 c9c9 6 l ( such that 2 Pile 3Pile 3 k = 2 / b2b2 b5b5 b8b8 a2a2 a5a5 a8a8 c2c2 c5c5 c8c8 l (b)(b) 100 and 2  Pile 2Pile 2 > 7 illustration. b1b1 b4b4 b7b7 a1a1 a4a4 a7a7 c1c1 c4c4 c7c7 Pile 1Pile 1 , c9 (Figure 4.24a). If the selected card is, to be specific, , which is the least 7, since 2  ... n 2 c7c7 c9c9 c3c3 c4c4 c5c5 c6c6 c1c1 c2c2 c8c8 = puzzle (#54) in the main section. Pile 3Pile 3 log  Three Pile Trick 100 2 This is one of several puzzles exploiting optimality of the decrease- The b3b3 b4b4 b5b5 b6b6 b7b7 b8b8 b9b9 b2b2 b1b1 The card in question will always be exactly in the middle of the pile The minimum number of cuts for a 100-unit stick is seven. log , b9; c1, c2, (a)(a)  Pile 2Pile 2 , of a piece is even, it is cut into two pieces of length 4.24 ... l 100 a4a4 a5a5 a9a9 a6a6 a7a7 a8a8 a3a3 a1a1 a2a2 The number of cuts (iterations) such an optimal algorithm makes for an Since cutting several pieces of a given stick at the same time is allowed, we need Let us denote cards in the three piles after the first deal as, say, a1, a2, = Pile 1Pile 1 respectively. The iterations stop after the longest—and,of hence, the all stick—has the length other 1. pieces stick is equal to n b1, b2, than 1, it is cut into pieces of lengths in pile 1, after the secondthe deal cards the that were piles in will pile lookpositions 1 as after in in the each Figure first 4.24b. of deal are Note theit now that piles. exactly is all If in either the the a3, three selected middle or card a6, is or now a9—it in, will say, be pile exactly 3—that in is, the middle of a pile in the final to concern ourselves only with findingthe a longest cutting algorithm piece that present reduces to the sizealgorithm size 1. of must This implies cut that the onwhose each longest size iteration is piece—and an greater than simultaneously optimal 1—by all halflength (or the as close other to this pieces as possible). That is, if the FIGURE Solution Comments 30. Cutting a Stick Solution by-half strategy. This strategy was also used to solve the 31. The Three Pile Trick the first tutorial. For a two-dimensionalRectangular Board version of the problem, see the selected by the chooser in the final layout. Algorithmic Puzzles 106 nwri h mletpwro hti rae hno qa to equal or than greater is that 2 of power smallest the is answer h otasmn httewne ottefis ac.Ti ilrqien more no require will This match. first the lost to winner up than leaf the this that from assuming a path find root the matches, follow the played and the winner all tournament’s representing the tree representing the leaf In follows. that as tournament organized single-elimination be own their can play made be can players These else. httunmn re aesm neetn plctosi optrscience computer out pointing in worth applications also interesting is It some [Knu98]). algorithm’s (see course. have the of trees counts, what step tournament of different that interpretations the different to leads The is it. step play—in of matches rounds individual either or as steps—understood of number the about ask questions Tournament Single-Elimination 32. in included also was It 143]. p. [Bac12, classic 17th-century Recreations Mathematical his in Bachet the by of analysis simple question. in a puzzle the which solves in algorithm given situation a a of output illustrates puzzle This analysis. and Solution deal, second and first Comments the after 3 and 1 than other case piles the in be respectively. also was would card this that selected see a to easy if is final It the in card. card that selected identifies the uniquely containing layout pile the out Pointing 4.24c) (Figure layout Solution Comments tnadntto o onigu otenaetinteger, nearest the to up rounding for notation standard If 1. to the reduced until is continue player rounds remaining the of and number half, by players remaining of number the reduces h tournament. the 3 ai n Pseudo-Magic and Magic 33. assigned opponent no have they because round next them. the to to directly players of Counting Bye n oe,adexactly and loser, one n = atnGrnricue iia uzei his in puzzle similar a included Gardner Martin mentioned was trick the 328], p. [Bal87, Coxeter and Ball to According .If b. .Tescn-etpae a eaypae h ott h inradnobody and winner the to lost who player any be can player second-best The c. 0 h ubro onsi qa to equal is rounds of number the 10,  log n 2 = n .Tettlnme fmthsi qa to equal is matches of number total The a. h nwr are answers The − 2 h oraetcnb osdrda loih,adtefis two first the and algorithm, an considered be can tournament The design algorithm of ideas general some on based are tricks card Many k uze(16 nti okdaswt ys hc r transfers are which byes, with deals book this in (#116) puzzle , matches. 1 h oa ubro onsi qa to equal is rounds of number total the n − yMuieKathk[r5,p 317]. p. [Kra53, Kraitchik Maurice by oesne ob rdcdt e igewne of winner single a get to produced be to need losers 1 n = and 3 n ≥  log o at a n b,respectively. (b), and (a) parts for 3 2 n 10 sntncsaiyapwro ,the 2, of power a necessarily not is = aha!Insight 4.  n log k − = 2 :ec ac yields match each 1: n log Gr8 .6.The 6]. p. [Gar78, n  o xml,for example, For . hti,uigthe using is, that , 2 n ahround each : 107 Solutions 3 3, × − n , with the n ... , 3, respectively. ... − 5. n , = 3 magic square is also n ... × 3. 5 9 9 1 1 = n puzzle for 4 4 3 8 8 puzzle (#29)), the puzzle’s objective 3 square at the upper left corner of an 2 2 7 6 6 1 (Figure 4.26). × 3 magic square must be filled with number 5 → × 5 is shown in Figure 4.25. 9 9 5 1 1 = 3 by making any of the eight magic squares of order 3 n of the table with the contents of rows 1, 2, 4 4 3 8 8 Magic and Pseudo-Magic = n n 3 with numbers 1 through 9 to have a magic square there , Magic Square Revisited > ... n the answer is obvious, because any 3 , 3 3 square at the upper left corner with numbers forming any 3 The algorithm’s idea is based on the incremental approach (see the × = Solution to the The largest number of coins that can be placed is seven. n 3 magic square, ignoring the parts of some squares, if any, that fall outside 3 square formed by the first three rows and columns 2, 3, and 4 will be a 4.25 × table where × n b. For This will make both lines connecting point 1 with points 4 and 6 unusable for With no loss of generality, we can start by placing the first coin on point 6 and a. Since the central square in a 3 Alternatively, the algorithm can be phrased as tiling the table given with the Fill the 3 × can only be achieved for Then fill rows 4, 5, a pseudo-magic square. If we fill a 3 (see the solution to the respectively. An example for corresponding entries at the first three cells at columns 1, 2, the table. magic square. Then fill the first three cells of columns 4, 5, same 3 n given there. another coin placement. Following the logic of the greedy strategy, we should 34. Coins on a Star then moving it to point 1, denoted 6 and then copy the contentsthe 3 of the first column as the contents of column four, Solution Comments FIGURE pseudo-magic square. Similarly, if we copy thea first pseudo-magic row square into in rows the 2, fourth, 3, we andthe will 4 following get and algorithm the for first the three task columns. in This question. leads to first tutorial) starting with the smallest instance of Algorithmic Puzzles 108 n atclrmto fgahrpeetto hne respectively. change, representation graph of method particular a and hnlfigvrie n n arigte nteopst ie fthat of the sides of representation star. opposite puzzle’s this as the from well 4.27a. immediately above—as on Figure mentioned solutions—follow them solution in alternative The several carrying depicted 4.27b. Figure graph and in the graph 4 carrying the yields yields and and graph graph 6 8 the vertex vertices lifting of and lifting side graph Then right the the of to side over left 4.26 the it Figure to in graph over the it of carrying 2 and vertex Lifting strategy.) discussion been change tutorial’s representation first have the the in of mentioned could was method (This coin method. strings” eighth and the which from there point coins seven unoccupied moved. placing no after because be coins, will eight place cannot we Obviously, seven example, ends moves: For of it sequence placed. that following been so the has by coin placed coin next of be previously the can line, the coins move usable which always a from to an point along is on the this there it at do it placing to moving try way by easiest should The line we placed. course. unusable one, be first an to the of still after point coins lines coin the unoccupied unusable each for of for lines that number usable implies the of This minimizes number that the manner maximizes hence a and in coin each placing try FIGURE Comments nlddi uhpzl ok s[u5,p 3] Sh8 .1] n [Gar78, and 15], p. strategies. [Sch68, design 230], been to p. related has closely [Dud58, it is It as times, 38]. p. books modern puzzle In such 5.R.6]). in Section included [Sin10, (see centuries for known ifrn esoso hspzl,as nw sthe as known also puzzle, this of versions Different lentvl,w a ov h uzeb uflig h rp yte“buttons the by graph the “unfolding” by puzzle the solve can we Alternatively, 4.26 6 h trfrpaigcisa t vertices. its at coins placing for star The → h w ouin ie bv aeavnaeo h reystrategy greedy the of advantage take above given solutions two The 1 , 3 → 6 7 6 , urn’ Puzzle Guarini’s 8 8 5 → 3 , 5 → 8 , icse ntettra nalgorithm on tutorial the in discussed , 2 → 4 1 5 , cormPuzzle Octogram 7 2 → 3 2 , 4 → 7 . aebeen have , 109 Solutions 6 3 8 1 0 2 3 0 3 2 0 (b)(b) 5 3-pint jug3-pint jug 4 7 0 5 2 2 0 5 4 5-pint jug5-pint jug 2 6 puzzle. 8 3 3 6 6 1 1 3 8-pint jug8-pint jug Three Jugs 1 4 6 1 2 3 4 5 (a)(a) Step#Step# 5 8 7 Solution to the Unfolding the graph of Figure 4.26. is a list of items, which, as its name implies, operates like a queue of The sequence shown in Figure 4.28 solves the puzzle in six steps: 4.28 4.27 queue A Although the solution can be obtained by trial and error, there is a systematic way 2 customers to a single cashier: the customers are served in the order they arrive. of getting to it. We can represent a stateindicating of the the jars by amount a of triple of water nonnegative integers inThus, the we start 3-pint, with 5-pint, the and triple 008. 8-pint Wecurrent jugs, will state respectively. consider of all the legal transformations jugs from to a of new the possible queue—one states. of the To basic do data this, structures we in computing. will take advantage FIGURE Solution FIGURE 35. Three Jugs Algorithmic Puzzles 110 euneo h uu otns hr h usrpsso h tt aeswhen labels state time: the first the show for subscripts assigned the are they where contents, queue labels the of the sequence follow time, puzzle. from the first solve state the that transformations front for of the sequence reached shortest delete is the get then state to backward and desired queue, the the After to queue. the them add it, from reachable n Comments steps: six of number minimum transformation the following in the puzzle the get solves we that backward, sequence 341 of that from labels the Tracing the all label queue, the of front the at state the encountered For 4—is a time. containing first triple the state—a for desired a until steps following the the the called called queue, end, other the the of to end added one from deleted are Items Solution n iu nisclm egbr h te aei ymti.Tu,ltu prove us let Thus, symmetric. neighbor is row case its other in the put neighbor; column is its plus in a minus when a case and the consider will We cells. neighboring sign. can same column, one the every contain solutions, have row, or alternative every solution than as previous rather the course, in Of minuses and question. pluses the in either interchange Under cell sign pluses. opposite the with the filled below with is neighbor or row one above last exactly have the will until cell on, every so scheme, and this again, pluses with 5 and 4 6 iie Diversity Limited 36. also (see [Twe39] Tweedie K. representation C. surprising M. Ivar 4]). a by by Chapter [OBe65, by discovered other solved coordinates the trilinear be and the also applet, in can visualization puzzle a The to [Pet03]. link Peterson a Bogomolny Alex contains by one which columns: [Bog00], online MAA two in found be can developments, search exhaustive an has clearly algorithm flavor. The simplicity. graph this of draw sake not the did for We explicitly graph. state-space puzzle’s the of 5.2]) Section [Lev06, sodd. is 008 251 323 h plcto fti loih otepzl’ aayed h following the yields data puzzle’s the to algorithm this of application The If norapiain eiiilz uu ihtegvnsaetil 0 n repeat and 008 triple state given the with queue a initialize we application, our In fw u lsi h pe etcre,w aet u lsadamnsi the in minus a and plus a put to have we corner, left upper the in plus a put we If oeitrsigtdisaotti eyodpzl,isvrain n later and variations its puzzle, old very this about tidbits interesting Some n , , | see,oecnfiltetprwwt lss os2ad3wt iue,rows minuses, with 3 and 2 rows pluses, with row top the fill can one even, is 305 017 332 008 107 | h uzehsaslto if solution a has puzzle The 332 , 008 h ouinmmc h so-called the mimics solution The | 053 017 , 026 → 008 , 341 323 | 053 053 251 | 026 , → 035 , 152 323 305 332 rear , → 350 | 152 . 026 n 305 see,adi osnthv ouinif solution a have not does it and even, is , 206 | → 035 026 206 , 350 rat-rtsearch breadth-first | 206 → , 323 , 251 107 front, 053 152 → | 350 | 107 n e tm are items new and 341 , 323 , . rvra (e.g., traversal 251 , new 332 206 | 035 states | 111 Solutions n 8 × 1 and counters counters − Then two n k . n k columns of the n 1, two counters in , however, because 4, which appeared in After that, + . k is odd. 1 = n n 7). + 1 of column rows and k n = − n n (see Figure 4.29a for the case of k 3, and so on, until rows Counters Problem - . n + 2 and and 2 k − k n 2, and and so on, until finally counters are columns as follows. (We assume that rows and + k k a solution can be obtained by placing two counters , 0 Queens Problem of columns - n > n k , 1 counters need to be placed into 1 and + , a solution can be obtained by identical placement of n (#140) that do not have a queen on the same square of the board. k k − 2 2 in rows 4 and 5 of column n the problem can also be solved by interposing two solutions to the [Loy60, Problem 48] considered the puzzle for an 8 The puzzle is motivated by its instance for , = = , 2 columns and the last n 4 Since 2 n k + ≥ k is even, and that it does not have a solution when -Counters Problem n n n 8). For even For odd For Queens Problem = - board with at most two counterstwo counters in have the to same be placed row in or each in row and the column. same column, exactly 37. 2 A. Spivak’s collection [Spi02, Problem 67b]. are placed in the right partcentral of square the to board those symmetrically in with the respectcolumn left to part: the two board’s counters are placed in rows 2 and 3 of placed in rows board with the additional stipulation that two counters must be placed on two counters are placed in the first and last rows of column in the first in rows 1 and 2on of until column 1, counters two are counters placed in in rows rows 3 and 4 of column 2, and so rows 3 and 4 of columns 2 and of the last column (see Figure 4.29b for the case of columns of the board are numberedPlace top two to counters bottom and in left the to first right, two respectively.) rows of columns 1 and it is, in fact, easier than the n This is hardly an advisable way to solve the 2 Comments Solution Comments that if we put pluses in the first2, two we cells of will row have 1 and to acells fill minus of the in the remaining row first cells cell 2 of of with row neighbor row with minuses. 1 a Since plus with above the pluses it, the first andBut second the cell cell then in remaining in the row 2 the third will second cell havein to row in contain row row a already 1 minus. 1 has already will has a a havethe neighbor remaining to with cells contain of a a row minus plus 1 belowin will since it. have row the By to 2 the second contain will same a cell have plus, argument, tominuses and all contain because all a their the neighbors minus. remaining in But cells row then 2 all alreadyThis have the implies the that cells plus row in neighbors 3 row in cannot row 3 be 1. pluses. must last Row contain but 4 must be can followed be by eitheron. row last (More 4 formally, or filled the with must same arguments all be can followed beThis made with via the proves mathematical induction.) all that plus the row, andwhen puzzle so has no other solutions than those described above n Algorithmic Puzzles 112 -ermne n qaettoioi lal ae nteivrat(parity invariant the 15 on with based tiling clearly of idea. is coloring) tetromino and proof square impossibility force 1 The brute and T-tetrominoes on strategy. either divide-and-conquer based the as or T-tetrominoes and L-tetrominoes, tetrominoes, Solution same the gave 8 authors both an While for that diagonals. line, and solution straight columns, any rows, in to be limited shall not pieces is, three no that imposed requirement also stringent 317] more Problem a [Dud58, Dudeney Henry board. the of squares central FIGURE Comments lascvra d ubro aksurswietenme fsc qae on squares such of number the while squares 8 an dark of tetromino number square odd 1 an and cover T-tetrominoes always 15 tetromino Hence square squares. single darks a two whereas covers odd, always them—is of number odd any T-tetromino— by one hence by and covered squares dark say, of, number The tetromino. square nabtaysz.Frafrhrdsuso ftepolm e hpe nMartin in 5 Chapter see problem, the of discussion Gardner’s further a For size. arbitrary an oetlsaogtebadrwt opsiiiyt oe h w eann squares 4.30e). remaining (Figure two row the first cover the to two in possibility putting no continue with to boarder necessary the it along makes board tiles the more of corner a cover to tile a such 8 ermn Tiling Tetromino 38. hti ahcs h iigo n ure ftebadi eetdfrtethree the for repeated is board the of quarter one of tiling quarters. Note other the 4.30. case Figure each in in shown that are T-tetrominoes and L-tetrominoes, tetrominoes, ial,i sipsil otl n8 an tile to impossible is it Finally, ti mosbet oe n8 an cover to impossible is It × hsbadi even. is chessboard 8 4.29 ers ie oTado Chiphers Trapdoor to Tiles Penrose iig fa 8 an of Tilings ouin o2 to Solutions n a osdrtetlnswt tagtttoios square tetrominoes, straight with tilings the consider can One × (a) or,Ddnysvrinrmisusle o orsof boards for unsolved remains version Dudeney’s board, 8 -onesProblem n-Counters × × hsbadwt tagtttoios square tetrominoes, straight with chessboard 8 hsbadwt -ermne.Ide,putting Indeed, Z-tetrominoes. with chessboard 8 × hsbadwt 5Tttoiosad1 and T-tetrominoes 15 with chessboard 8 o (a) for [Gar97a]. n = n (b) and 8 (b) n = 7. 113 Solutions (b)(b) (d)(d) (e)(e) (c)(c) (a)(a) Tiling a chessboard with tetrominoes. (a) Straight tetrominoes. (b) Square 4.30 tetrominoes. (c) L-tetrominoes. (d) T-tetrominoes. (e) Z-tetrominoes (failed). FIGURE Algorithmic Puzzles 114 9 or Walks Board 39. [Gol54]. ih qae.Oeo uhpts hc xlistebadssmer,i hw in at shown end is and symmetry, start board’s the must 4.31b. exploits squares Figure which the paths, such all of through One path squares. a light squares, dark of number the board a the squares of squares of the impossible. colors all is through 4.31a the Figure path Since in a squares. such it alternate, light must 4.31a), than through (Figure goes squares path chessboard dark a more as six alternatingly have squares will board’s the colors one If odtrieteeitneo aitnpt na rirr rp sknown is graph arbitrary an in path Hamilton a algorithm of efficient either. this no existence of however: the absence easier, determine The problem point. to the starting make its not to does return to to requirement required comments not the is (see path Hamilton circuit Hamilton a squares. adjacent “connect” Unlike edges and squares board’s the represent vertices whose algorithm on tutorial the (see idea invariant techniques). the analysis exploit to ways used frequently Solution Comments FIGURE ahtruhalissquares. its all through path a hspzl sfo h eia ae nploiotln ySlmnGolomb Solomon by tiling polyomino on paper seminal the from is puzzle This ic h ubro ih qae ntebado iue21bi oeb than 1 by more is 2.11b Figure of board the on squares light of number the Since at()i ae nPolm49i .Sia’ olcin[Spi02]. collection Spivak’s A. in 459 Problem on based is (b) Part a of existence an for asks problem the that Note 4.31 opt hog l h qae ftebadi iue21ai possible. is 2.11a Figure in board the of squares the all through path No a ooigo h rtbadgvn b ooigo h eodbadwith board second the of Coloring (b) given. board first the of Coloring (a) h ouin aeavnaeo ooigoeo h most the of coloring—one of advantage take solutions The (a) h csa Game Icosian The aitnpath Hamilton (b) nagraph a in #7) a (#27)), 115 Solutions is n 3if / n puzzle represented by the 3 4 8 9 , discussed in the first tutorial, is from [Fom96, 2 1 Four Alternating Knights [Gar78, p. 36]. 7 6 is not divisible by 3. n Guarini’s Puzzle if n aha!Insight The puzzle’s solution exploits two themes in algorithmic problem Initial state of the The minimum number of switches that need to be flipped is The puzzle has no solution. 4.32 As explained in the tutorial on algorithm design strategies, the initial state of the The knights can move only to adjacent vertices of that graph preserving their It is not difficult to realize that the final state of the lights depends only on This variation of —say, clockwise—starting with that switch/light. Then to have light 1 to remain the parity (odd or even)not of depend the number on of the timesthat order each needs in switch to is which be flipped determined the and iswhich switches does which should are of be the manipulated. left switches Therefore shouldlight, in we all be the need flipped either off once flip and position its switchinitial to while positions have leaving or the all flip two adjacent the all switchesto these lights in be three their flipped. on. switches. Let To us Clearly, number turn at then least on lights and one a their switch corresponding needs switches from 1 to puzzle can be conveniently represented by a graph in Figure 4.32. clockwise (and counterclockwise) order: the two knightsthe of two one knights color of followed the by otherrequires color. the Since four the knights of objective different configuration colors of alternate, the the puzzle puzzle cannot be solved. divisible by 3 and unfolded graph. Solution Comments FIGURE 40. Four Alternating Knights Solution solving: representation change (the board’s graph and(the its knights’ unfolding) clockwise and order). invariant Problem 2, p. 39].M. Gardner in A similar variation of the classic puzzle is41. mentioned The Circle by of Lights Algorithmic Puzzles 116 epciey hntepzl a w ymti solutions: symmetric two has puzzle the Then respectively. MtCnrl.Test etosta eoo h uzefor puzzle Canada the of Saskatchewan, demo a Regina, that in mentions site Regina The of [MathCentral]. University the at maintained is which Central— Math sophisticated more a require any state—would approach. designated from some transformation to lights a of requiring state one given version—the general more its thinking, ngnrl pedn CadGH and WC appending general, In nyb ett nH For H. an to next be only 2 h te ofGa-abg Puzzle Wolf-Goat-Cabbage Other The 42. version. one-dimensional this Comments and 2 (numbered switches adjacent its state, final the in on Solution wths hc ssalrta ipn l the all flipping than smaller is which switches, n ero h ouin for solutions the of rear and osbei n nyif only and if possible ymti ouin:WH n GHCW. and WCHG solutions: symmetric a suewtotls fgnrlt htti ouinhsalits all has solution the this not that is we generality this them, of on which imposed loss restrictions for without symmetric contradiction. solution assume the by have may a G’s this and exists prove W’s there the can Since that. We case. contrary, ordering. the counters’ to the of Assume, ends two the at si a h aefor case the was it As above. ntemteaismsu nGesn emn.Todmninlvrin of versions Two-dimensional Germany. puzzle— Giessen, the in museum mathematics the in ipdo ohntflpe.I h omrcs,sic n switch and 3 switch case, former the In flipped. not both or flipped lob ipd otnigti rcs ecm otestaini hc l the all which in situation the once. to flipped come be we must switches process this continuing flipped; be also o l te ausof values other all for ouin for solutions ipd hti,tesice ubrd1 switch numbered third every switches light have on will the turn process to is, this flipped of that be Continuation 5. must flipped, and 4 4 switch lights on; as 2 well light as leave 3 to flipped be not must 3 h uzewsofrd steNvme 04polmo h ot,on month, the of problem 2004 November the as offered, was puzzle The h e bevto eei htaWmyol enx oaC n may G a and C, a to next be only may W a that is here observation key The ntelte aewe wth1i ipdadsice and 2 switches and flipped is 1 switch case—when latter the In h ouin for solutions The h atta hr sn te ouinflosfo h olwn argument. following the from follows solution other no is there that fact The WCWC e ,G ,adHrpeetawl,aga,acbae n hunter, a and cabbage, a goat, a wolf, a represent H and C, G, W, Let elnsMgcSquares Magic Merlin’s ... n lhuhw eeal osletepzl yesnilybrute-force essentially by puzzle the solve to able were we Although = nItre evc o tdnsadtahr fmathematics, of teachers and students for service Internet an WCHGHG ilstetosltosfrayvleof value any for solutions two the yields 1 n n n n = . samlil f3 o such For 3. of multiple a is = a eotie yapnigW n Ht h front the to GH and WC appending by obtained be can 2 n 1 , = n ouinms aeaWcutradaG-counter a and W-counter a have must solution any ... n ,ti meitl mle httepzl a two has puzzle the that implies immediately this 1, = GadGHGH and HG ogtWWHH n GHGHCWCW. and WCWCHGHG get to 1 and n ihsOut Lights − , ie otefotadra fthe of rear and front the to times 1 4 .., ,... n wthstemnmmneeded minimum switches—the n ae nfc,bte nw than known better fact, in —are, s hsatraieflp only flips alternative this ’s, 3 ... k + GHCWCW 1 .., ,... n utb ihrboth either be must ) n n , = n hc r given are which n r not—switch are a exhibited was 7 − ... n n ,wihis which 2, ’ inside W’s − CW. must 1 n / 3 117 Solutions H’s to form a n 1 C’s adjacent to is even. After that, [MathCircle]. n + n C’s to form a sequence [Kra53, p. 214], the puzzle n The Math Circle 3 instance. is odd and two coins if = H between the W and G and one way to put n n 1 G’s must be interleaved with ... − Mathematical Recreations n 1 W’s must be interleaved with H inside the solution’s ordering. Finally, there is just one way − C and HGHG ... n ... The above algorithm is based on two algorithm design strategies: The solution to the puzzle can be considered based on decrease-and- C and the other The puzzle can be solved in two weighings. Start by sorting the list in increasing order. Then repeat the following ... 1 times: If the first inequality sign is “<,” place the first (smallest) number in Start by taking aside one coin if If the first weighing does not result in a balance, take the lighter group and, if the Since the puzzle cannot, obviously, be solved in one weighing, the above The problem was posted on a web page of According to M. Kraitchik’s − them, which is impossible. Thus,ends; any solution the must other have a W and a G at its two sequence HGHG them between the G and W without violating the puzzle’s constraints. number of coins in it is odd, addbe to it genuine). one of Divide the coins all initially set theseIf aside (which coins they must weigh into the two same, equal-sizeheavier; all otherwise, groups these they and contain coins the weigh are fake, genuine which them. is and lighter. therefore the fake coinalgorithm is solves it in the minimum possible number of weighings. divide the remaining eventhem number on of the coins opposite into pansare two genuine of equal-size and the groups the scale. and fake Ifset-aside put coin group they is of among weigh one the the or coins two same,the set former coins all weighs aside. against less, these So the the fake we same coins coin number can is of weigh lighter; otherwise, genuine the it coins: is if heavier. to put CWCW the first box; otherwise, place there thenumber last from (largest) the number. After list that, and delete the the remains, box place it it was in put the remaining in. box. Finally, when just a single number Solution Comments Solution Comments the solution’s ordering. But then it would have to have 43. Number Placement 44. Lighter or Heavier? transform-and-conquer (presorting) andone). Note that decrease-and-conquer it does not (decrease-by- give all possible solutions. is due to Aubry, who considered its conquer applied bottom up: the solution is obtainedthe by same solving smaller puzzle instances first of and then extending their solutions to form the same patterns. n CWCW Algorithmic Puzzles 118 qae r 1 )ad(0,10,rsetvl,asqec f6 oe uhas such finish moves and 66 start of its sequence a if respectively, Thus, 100), moves. (100, its and 1) of (1, pair are every squares after diagonal main the on stay 5 ngtsSots Path Shortest Knight’s A 45. 41, p. [Bos07, students school middle for 4]. collection Problem Russian a and 72], Problem o ag h rbe’ ntne(ee h ubro on)i.Aohrsuch Another is. coins) of number is the book the (here, of in irrespective example instance weighings) problem’s two the (namely, steps large basic how of number same the in solved h ahta itnet h etnto qaea uha osbe ti not is It arbitrary possible. an as for question much The as course. square of destination unique, the to distance decreases Manhattan algorithm the the step each on since techniques) design algorithm on tutorial Solution Comments Solution Comments nqeto.Hr h ahta itnebtentesatadfiihsursis squares finish and start the between distance (100 Manhattan squares the two between Here columns question. of number in the plus so-called rows of the number by the as board computed the on squares two between ounaeo h he ifrn oos If colors. different three the of are column 6 rclrArrangement Tricolor 46. yn oeta ,tekih ilne tlat6 oe orahisdestination. its optimal. reach indeed is to above moves given 66 moves least of sequence at the need that will proves knight This the 3, than more no by ii l fte r ftesm oo.I ae() ohn biul ed obe to needs obviously nothing (i), case column. first In the color. in and counters same color, the the same with the of done of are are them two exactly of (ii) all colors, (iii) different the of are them of three three the of sizes decreasing are of problem. column boards the first the solve will for the rearrangement in a counters such repeating three colors; the different that so rearranged be can h qain1 equation the number (The problem. the solves lhuhtekih antmv ln h tagtln oadisga,i can it goal, its toward line straight the along move cannot knight the Although ntne fti uzeaeicue napzl okb ikHs [Hes09, Hess Dick by book puzzle a in included are puzzle this of Instances ie h aueo h ngtsmvs ti ovnett esr h distance the measure to convenient is it moves, knight’s the of nature the Given osdrtecutr ntefis oun hr r he osblte:()all (i) possibilities: three are There column. first the in counters the Consider − (1 1) , 1) + If 66. is moves of number minimum The − (100 n h uzepoie eyrr xml fapolmta a be can that problem a of example rare very a provides puzzle The h ouint h uzecnb osdrd“rey sethe (see “greedy” considered be can puzzle the to solution The + (3 = 3 , − ,tepolmi led ovd l he onesi h only the in counters three all solved: already is problem the 1, k 2) = 1) − tc fFk Coins Fake of Stack A 100.) = ngtsReach Knight’s n (4 × 9.Sneoekih’ oecndces hsdistance this decrease can move knight’s one Since 198. , 4) n board. −···− k ftomv dacscnb bandfrom obtained be can advances two-move of uze(10 el ihamr general more a with deals (#100) puzzle (97 n (#11). , > 97) ,w ilso httecounters the that show will we 1, − (99 ahta distance, Manhattan , 98) − (100 , 100) hc is which 119 Solutions counter 1 of them can be − n naWorB 4 chessboard (Figure 4.33), it × must contai 4 chessboard, it is much easier to solve it R R R × a B counter must contain Case (ii) Case (iii) Although the puzzle can be interpreted as a question about Hamilton The algorithm solving the puzzle takes advantage of the decrease- blue counters on the board and no more than a. Since a path through the exhibition must visit each room exactly n R R W Finally, consider case (iii). We assume, without loss of generality, that the three Consider case (ii); we assume without loss of generality that the two counters of b. On coloring the rooms as squares of a 4 The puzzle has been included in A. Spivak’s collection [Spi02, Problem 670]. becomes obvious that any pathsquares through of the alternating exhibition colors. will Since havefirst to the and pass last total squares through of must 16 bedoor rooms colored pairs in have that the to opposite need be colors. to The visited, besymmetrically, possible (A4,B4), the open outside (A4, are B2), (A3, (A1, B3), B1), (A3, (A1,(of B1). Figure B3), the 4.34 several (A2, shows possible) B2), one path for (A2, each B4)the of and, room the doors first indicated four by pairs thethe listed path floor above. plan intersection are Of with assumed course, the to all square be open boundaries as on well. directly by exploiting the standard square coloring argument. counters in the first column are red. Sinceat each least of one the counter three of rows the must color then othera contain than counter red, we and can swap scan, it say, rowcase with 3 (ii). the to find counter such in the first column to get the situation of in the third row, atalgorithm in least question can one scan the of first two themcounter rows starting must is with column be encountered; 2 after in until a a the blue the blue first red counter counter two in is the rows. found, first it Hence column. should the be swapped with the same color are, say, red andin they the are first in column the and first the twothere third rows, are row whereas is, the say, counter white (see the diagram below). Since Comments Solution Comments paths in the graph representing the 4 47. Exhibition Planning by-one and transformation ideas, which aredesign discussed strategies. in the tutorial on algorithm once, it will haveimplies to that enter the minimum and ofdoor leave 17 and one each doors exit need room door. to through be different open, doors. including one This entrance Algorithmic Puzzles 120 ,6 ,ad2 cugt ytefloigagrtm If algorithm. following the by McNuggets containing 20 boxes and the of 9, combination 6, some as 4, represented be can (a), part in listed 11. and 7, 5, 3, 2, 1, numbers: FIGURE Solution Numbers McNugget 48. FIGURE .Eeypstv number positive Every b. B1 A1 4.33 4.34 .I sovosta h olwn i ubr r o McNugget not are numbers six following the that obvious is It a. ite-ompa ooe sachessboard. a as colored plan Sixteen-room orptstruhec omwt h akdetac n xtdoors. exit and entrance marked the with room each through paths Four A2 B2 B1 A1 n fMNges hc sdsic rmtesxvalues six the from distinct is which McNuggets, of A2 B2 B3 A3 A1 B4 A4 A2 n ≤ B3 5 h following the 15, B4 121 Solutions . 2c 2c 9 mc mc and · 4 and 0 and 1 k → → → → − ≥ + c c m m n 6 k McNuggets · → → n → → 1 problem whose 2c 2c = 2c 2c be presented as a where , ). Using one of the r 6 r 15 → → · , → → not + 6 + 1 c c c c · k + 1 4 (12 → → 4 → → + · + = 4 1 k · 2m 2m 2m 2m 12 = 2 4-piece boxes, we get as 4 − → → → k = n → 10 n , Three Jealous Husbands 9 14 mc mc mc (see, e.g., [Mic09, Section 6.7]). · mc , 9 1 · → → → → = 1 9 + , 2m 2m 2m 2m 4 4 · · 12 by 4 (i.e., given above and 2 → → 1 → → r − c c c = = c + n 8 , 13 → → → 6 , → · 6) 2c 2c 1 2c Frobenius Coin Problem · 2c = → For the above solution to work, it suffices that one of the missionaries The above algorithm is based on the decrease (by 4)-and-conquer → → of division 6 → , The problem can be solved by creating a state-space graph for it m c r solve the problem by the same method (i.e., recursively) for m c 4 4(or 2 , 3). This yields the representation of · · → 1 3 → → 15 → ≤ r = = > 2c mc 2c mc Alternatively—to avoid the recursion—one can find the quotient The four paths from the initial-state vertex to the final-state vertex, each 11 edges The solution is based on creating a state-space graph, which is a standard method The puzzle is a 19th-century variation of one of the three river-crossing puzzles In general, finding the smallest positive integer that can 4 n ≤ 12 0 remainder add one 4-nugget box to that box combination. four combinations for 12 Comments Solution Comments If combinations can be used: in total. and two of the cannibals can row. for solving such problems. For an alternative graphical solution, see [Pet09, p. 253]. in the medieval collection of(c.735–804). It recreational is very problems closely attributed related to to the Alcuin of York strategy. The algorithm does not use 20-piece20 is boxes a at multiple all. of (This 4.) happens Obviously, because the any above five algorithm 4-piece can boxes be in replaced the by solution one obtained 20-piece by box. linear combination of a given set of natural1 numbers is with known greatest as common the divisor 49. Missionaries and Cannibals (Figure 4.35). long, represent the solutions with the minimum number of river crossings: two-couple version is solved invariations, the see book’s David Singmaster’s first annotated tutorial. bibliography For [Sin10, Section other 5.B]. references and Algorithmic Puzzles 122 alms ewie ic h nta ubro ht al sodadteprt of parity the and odd same. is the balls stays white balls of white of number number initial the the since white, be must ball 16 whereas number odd single an is a 1 when because parity. balls, white, even. be white is same cannot 16 the it and bag, retain the black will in 20 remains balls with ball white starts balls of algorithm black of the number number if the the Therefore, and 1, by parity, decrease its will change balls of will number total the are, bag the puzzle. the of part eiae oitriwquestions. interview to dedicated be cannot puzzle the here. that case the indicates not invariant is an this solved, puzzles of majority a in although FIGURE Comments Solution Ball Last 50. ersne yrcage,wt h w bars two the with rectangles, by represented hwn h otslcto.Tevrie orsodn oteiiiladfia ttsare states participants. trip’s final the and indicate initial labels the Edge to bold. corresponding in shown vertices The location. boat’s the showing 2c 2m 3c 3m b fteeae2 lc al n 5wieblst ei ih igeremaining single a with, begin to balls white 15 and balls black 20 are there If (b) from removed balls two color what matter no that note to difficult not is It (a) ifrn ntneo hspzl a efuda tcIt—n fsvrlsites several of [techInt]—one at found be can puzzle this of instance different A mc 4.35 h eann alms ebakfrte()pr n ht o h (b) the for white and part (a) the for black be must ball remaining The tt-pc rp o the for graph State-space c m h ouini biul ae nteprt nain.Nt that Note invariant. parity the on based obviously is solution The 2c m 3m 3m 2c 3m 3m c c c m 2m 2c c c 2c 3c 2c 2m 2c c isoaisadCannibals and Missionaries mc || eoigtervradtesae oval shaded the and river the denoting 2c 2c 2m 2c 3c c c 2c 2m c 3m 3m 2c 3m 3m c c m c uze h etcsare vertices The puzzle. 2c m c m mc 2c 2m 3c 3m 123 Solutions S + 1) 5040. − − . Thus we m J ( , 99 100 51 50 99 100 4951 4950 +···+ ...... ) mod 100 2 j + − , 100. , 1 99 ’s values between 1 and 99, 51 . Therefore Jill can sum up = 49 (50 J m = j ≤ J ≤ j = mod 100) mod 100 − − j J S ≤ 5050 (see the tutorial on algorithm ≤ − , 150 , = = 99 49 = if 0 if 50 m 2 is obtained as the difference 5050 ≤ / m ≤ j ) mod 100 j m j 1099 J j 49 5049 51 50 101 mod 100 5001 5000 4999 − ≤ mod 100 are the remainders of the division of and − ≤ − S J , × ( S ( 50 150 50 = if 0 if 51 = j ...... = 100 5040 and = j j j = = = , J − − m 50 and Then for the missing number 100 50 4950 150 100, from this sum: mod 100 . by the formula is 10, ) mod 100 = J we can still use the second of the above formulas, because then = m m m , − 12 12 = = 49 48 S 100 5049 5048 100 ( +···+ Since the sum of all the consecutive integers from 1 to 100 is equal to m − 2 +···+ = j mod 100 j by 100, which are the numbers formed by the last two decimal digits of is the integer between 0 and 99 formed by the last two digits of respectively + S j 1) m J − − , j J 1 given in the table below, run the range from 4950 to 5049, inclusive, and can m 5050 J + , Since adding three- and four-digit numbers in one’s head is not an easy operation More formally, the above formulas can be derived from the following property J by subtracting the sum of the numbers recited, 50 = and = 150 m to perform, the algorithm canof be all simplified the by sums. computing This fact just followsof the from last the two observation that digits the 100 possible values we have the formula the numbers recited by Jack andmissing then number compute this difference. For example, if the have of the modulo division: S and analysis techniques where this formula is derived), one canm find the missing number and if where where ( 51. Missing Number Solution J be uniquely represented by theirmissing number last two digits. One can then easily obtain the S Algorithmic Puzzles 124 o in not in coins the ftefk onis coin fake the of 2 onigTriangles Counting 52. [CarTalk]. National 2004 6, U.S. December the on of Talk” “Car listeners show to talk posed Radio Public was version particular This well-known. is between difference the by number missing and the represent we strategy: conquer 3 aeCi eeto ihaSrn Scale Spring a with Detection Fake-Coin 53. analysis algorithm 1]. on Problem tutorial the in discussed is example techniques. similar A analysis. Solution Comments Solution Comments ti o ifiutt oie(n rv yidcin httenme ftenew the of number the that the induction) on by added prove triangles (and notice small to difficult not is It t oa weight total its fteagrtmfrtefis e ausof values few first the for algorithm the of mle httettlnme fsaltinlsatrthe after triangles small of number as computed total the that implies o h aei e aftesz.W ilhv orpa hshligadweighing and halving this repeat to have will We size. searching the proceed half operation can set we a weighing in one fake after the given, for coins the half) nearly (or half h rbe frcvrn isn nee nasto h rtpstv integers positive first the of set a in integer missing a recovering of problem The h uzei from is puzzle The osdra rirr subset arbitrary an Consider h olwn al otistenme fsaltriangles small of number the contains table following The J n hnrpeettelte yisls w digits. two last its by latter the represent then and S ntefre aeadaogtecisin coins the among and case former the in  log h iiu ubro egig eddt urne identification guarantee to needed weighings of number minimum The be will There S 1 sfk.Hnew a rce erhn o h aeaogtecoins the among fake the for searching proceed can we Hence fake. is + h ouint h uzetksavnaeo h transform-and- the of advantage takes puzzle the to solution The h uzepoie ahrsrihfradeecs na algorithm an in exercise straightforward rather a provides puzzle The 2 W = n 3   1 · seulto equal is log ie before times 1 + + 2 3(1 n 3 ahmtclPuzzling Mathematical  2 3 . · ( + 2 n +···+ − gm 2 n hieaini qa o3( to equal is iteration th S +···+ 410 21 34 11 nT n 1) , of h ieo h rgnlst a egaate to guaranteed be can set, original the of size the , l h on in coins the all n m + ≥ 3( + ml rage fe the after triangles small 1 + + ( n on eetdfo the from selected coins 1 n 6 n 3 ( 9 : − n − = = = ) 1) 1)) 10 4 19 yA adnr[a9,p 88, p. [Gar99, Gardiner A. by S S = r eun;ohrie n of one otherwise, genuine; are ntelte ae If case. latter the in 2 3 ( n n − − T 1) n ( hieaincnbe can iteration th )for 1) n n after ) n + hiteration. th n 1 on ie.If given. coins . n n S > iterations contains .This 1. S 125 Solutions )  m 000, 2 , 559. , puzzle log 468 + = n such readings. 6 whose solution 2 1 squares. This 6 9 , 559 and 600 × 0 Twenty Questions , − log 1 rectangle creates a (  6 = puzzle in the tutorial w ), mn  Cutting a Stick 2 × (1) / 4 rectangle into eight unit h h W  , ( × 1  2 > / n w  Number Guessing 1 for + rectangle given into )  n 2 Breaking a Chocolate Bar / × n  m ( W All the readings without 1’s are obtained by filling six . = 6 ) n ( .)  W n 2 vertical cuts along the board’s lines—as close to the middle as As its one-dimensional version—see the The above algorithm is based on the descrease-by-half strategy.  log n The answers to the first and second questions are 468 Since any vertical (horizontal) cut of an 2 horizontal cuts along the board’s lines—as close to the middle as =  log )  m n ( 2 The answer to the first question can be computed as the difference between the The problem of detecting a defective coin is one of the most popular puzzle The earliest reference to this puzzle in David Singmaster’s bibliography [Sin10, W log total number of readings and thoseis without any obviously 1’s. equal The to total 10 number of readings respectively. number of cuts is alsomake sufficient as performed by the following algorithm. First, Hence, the total number of readings with digit 1 is equal to 10 is possible—of all the rectangles with the width greater than 1. Then perform 55. Odometer Puzzle squares with three cuts. TheTanton general in instance his book of [Tan01], the where puzzle hethe gives minimum is an number included of induction cuts proof by (p. of James 118). the formula for rectangle with width (height) not smaller than possible—of all the rectanglesgreater than (strips 1. with width equal to 1) with the height Solution Comments  Solution cuts are necessary to cut the Comments be reduced to 1. (Formally, theby the number recurrence of weighings in the worst case is defined display positions with one of the nine digits; therefore there are 9 (#30)—this puzzle exploits optimalitythat of the the variant decrease-by-half of this technique.than puzzle one Note that rectangle does at not a allow time stacking, (the that is, cutting more It is almost identical to the algorithm for the 54. Cutting a Rectangular Board types in recreational mathematics. Theless common version than with the one a with springproblem, a see scale balance the scale. paper is For by somewhat C. an Christen in-depth and discussion F. of Hwang this [Chr84]. game described in the book’s first tutorial. Section 6.AV], dates 1880; it concerns cutting a 2 on algorithm analysis techniques)invariant. exploits the quite different idea—that of an Algorithmic Puzzles 126 ilapa nalteraig h aenme ftms hrfr h total the Therefore 0 readings: times. the all of in digits number the all same of the readings time of the number all in appear will 6 iigU Recruits Up Lining 56. [CarTalk]. 2008 27, October on Talk” “Car show talk Radio Public general the apply to than rather tutorial. second specifics the in its discussed techniques exploiting by algorithm an analyze en aigi eaienme ftelretaslt au.Ti sachieved is This value. absolute largest the of if number negative a it making means Solution Comments Solution Comments h tesntcnrbtn otevleo xrsin(1). expression of value the to contributing not others the hssmcnb nepee stesmo egh fsget oeigteinterval the covering segments of at lengths endpoints of sum with the as interpreted be can sum this egt r otdi ihracnigo ecnigodrt il h difference the yield to order descending or h ascending either in sorted are heights h where eri nthe in recruit Since ifrnei egto daetmn htis, that men, adjacent of height in difference h odn po eecp.I sa cainlyueu olfragrtmanalysis. algorithm for tool useful occasionally an is It telescope. a of up folding the the called is (1) equality of side 7 ioac’ abt Problem Rabbits Fibonacci’s 57. goal. intended their execute contradicts to fact, eager in that, be manner to a appears in it who does man but orders simple-minded a as depicted is Schweik Schweik max max h oase h eodqeto,oecnsml oeta aho h 0digits 10 the of each that note simply can one question, second the answer To h eodqeto a ie sapzl olseeso h ..National U.S. the of listeners to puzzle a as given was question second The h neddodrws fcus,t iiieteaverage the minimize to course, of was, order intended The h uzealdst h eoo h ol-aosnovel world-famous the of hero the to alludes puzzle The 1 and − − n n yteCehwie aolvHšk(8312) nti aiia novel, satirical this In (1883–1923). Hašek Yaroslav writer Czech the by , h sfie,temlil 1 multiple the fixed, is h 1 n h min stenme frcut and recruits of number the is min [ n ( cwi uthv nesodhsodra n ominimize to one as order his understood have must Schweik r h ags n mlethihs epciey ihtehihso all of heights the with respectively, heights, smallest and largest the are h fe 2mnh,teewl e23piso rabbits. of pairs 233 be will there months, 12 After oefra ro ymteaia nuto sntdifficult. not is induction mathematical by proof formal more A . 2 ewe h aia n iia egt.Frayohrordering, other any For heights. minimal and maximal the between h u ( sum The to easier much is it cases some in that is puzzle this of point The i − hpsto.Sne( Since position. th ilapa a eotie soetnho h oa number total the of tenth one as obtained be can appear will 1 a s 1 n h ( h 1 | ) min h + 2 − and ( h h 2 h 3 − 1 − |+| h h max / 1 h n ) 2 eecpcseries telescopic h ) + a einrd u 2 smnmzdwe the when minimized is (2) Sum ignored. be can ihsm vras hc ae tlre than larger it makes which overlaps, some with 3 +···+ . h 1(6 ( − n h 3 − h − 2 · h h |+···+| 10 i h 1 , 2 ) 6 ( i ) / ) h n = +···+ n = eas ftepyia nlg of analogy physical the of because a engtv,isminimization its negative, be can − 1 600 , h 2 n h .., ,... − , n ( 000. 1 − h ) ]= n h − n n − h stehih fthe of height the is , 1 n 1 n − | ( ) h 1 h odSoldier Good The . magnitude n nteleft-hand the in ) − h 1 ) , fthe of (2) (1) 127 Solutions 1 2) = − 12 n 233 . devoted ( (0) 1 , which is F R ⎤ ⎦ 1 = + + 1. Obviously, n 11 144 1)  (1) = ), is equal to the ), written by the 5 R n Clearly, − ( , by using one of the . √ n 1 89 10 (1) n R 2 ( 12 F − F = R 1 9 = 55  (0) Fibonacci sequence ) 0 and Fibonacci Quarterly, Liber Abaci − R n ( 1), plus the number of rabbit ( 1 8 = F 34 + − , n rounded to the nearest integer. 1 n  ( (0) 5 7 F > R 21 1 √ n 1, + 2 n + −  2), the number of rabbit pairs at the end of 6 13 1 n 5 −  2) for √ n ⎡ ⎣ 2 . According to the problem’s assumptions, the 5 8 ( n − + 5 R 1 n 1 1, the number of rabbit pairs, √ ( 4 5  R > The Book of Calculation = 0. Also note that we could find 5 n + 1 3 3 √ ≥ 1) 1) n = + 2 2 − n ) differs slightly from the canonical ( 1) n , defined by this recurrence relation: n ( F 1 1 ( 1) for + R R = n 1. For every + ( = ) 0 1 2. Thus, we have the recurrence relation n F n ) ) be the number of rabbit pairs at the end of month = ( ( n n − F ( = R ( ) n R ) R n (1) = n ( n R ( ) R n From the algorithmic perspective, the puzzle specifies an algorithm and asks to The puzzle appeared in Let R ( to the Fibonacci sequence andBritish mathematician its Ron applications. Knott [Knott] In contains a particular, scoreFibonacci of the numbers. puzzles related website to by the the Italian mathematician Leonardo of Piza,other also known and as more Fibonacci, important inHindu-Arabic 1202. contribution numeral (The of system in the Europe.) book Theis sequence was one that of the solves the the promotion most problem interesting ofdoes and the it important sequences have ever many discovered. fascinating Notin only properties, many but areas it arises, ofbooks often nature and quite websites, and as unexpectedly, well science. as a Nowadays special there journal called exist a large number of usually defined by the same recurrence equation two well-known formulas for the Fibonacci numbers (e.g., [Gra94, Section 6.6]): determine its output. This is a relatively rarethem, type the of algorithmic object puzzle; is for to most of designan an algorithm given. algorithm rather than to determine the output of and R month but with different initial conditions, namely, pairs born at the endnumber of of newborns month is equal to number of pairs at the end of month and Comments The following table gives the values ofFibonacci the first numbers 13 terms of the sequence, called the Algorithmic Puzzles 128 n en ytrosadovos ahtm o hn bu t p 24). (p. it” between about alternate think that you things time those each obvious, of and one mysterious is in being “this 21]; that p. noted [Win07, he puzzles solution, mathematical a of writing book included second also his was into problem Winkler The Peter 669). by (p. book 1955 Boerner’s Hermann to origin of volume third Programming the Computer in of exercise Art an The as it included Knuth Donald arrays. dimensional otherwise, b h mleteeet in elements smallest the Solution Twice Sorting Once, Sorting 58. Comments aepstosin positions same xml,te r 3 are they example, b qa othe to equal lmnsin elements and lmnsof elements reult h adi column in card the to equal or hno qa to equal or than mle than smaller i as time, first the for rank cards’ the by a codn otepoet ttdaoe h adi column in card the above, stated property the to According nsome in a ooti hs ausi,o ore osr h sequences: simplest the The sort 9. to and course, 6 of are is, smallest values fourth these the obtain 8, and to way 4 are smallest third the 5, and 3 en htrow that means hrwwl oti the contain will row th j i  3  eeetsequences -element sthe is ≤ osdrnwaytocolumns two any now Consider hsuepce eutflosfo h olwn rpry fteeaetwo are there If property: following the from follows result unexpected This opoeti rpry consider property, this prove To = b b i  b j tef osdrdi hi rgnlpstosin positions original their in considered itself, 4 for j i = hpsto nsequence in position th hsals lmn in element smallest th a j h nwri zero. is answer The 8 i  A i A a = hsals lmn in element smallest th , ol aehd(tleast) (at had have would . i  fcus,ti rpryhlsfraydul otdtwo- sorted doubly any for holds property this course, Of h r mleteeetin element smallest 3rd the . r mle hno qa otecrepnigeeet of elements corresponding the to equal or than smaller are hsipisthat implies This 1 i b , ilb sorted. be will i  A . 2 I u xml,te r n 5 and 5 are they example, our (In .., ,... , htaesalrta reult hs lmnsin elements these to equal or than smaller are that A 1 , i = hsals ad fteclmsfrevery for columns the of cards smallest th n )Hence .) 6 and A n a and ,te the then ), 1 , a l B A B A . B 2   :5958 :3416, ic columns Since .., ,... :5589. a B :1346, r,rsetvl,1ad5 h eodsals are smallest second the 5, and 1 respectively, are, B i  , Ku8 .28 rbe 7;h lotae its traced also he 27]; Problem 238, p. [Knu98, k . ≤ B b hr are there and Frisac,if instance, (For i  A o every for b = i and a i  i hsals lmn in element smallest th , n lmnsin elements l b b where and ( B j i  , k B sgetrta reult a least) (at to equal or than greater is , the fe otn h ra’ oun,the columns, array’s the sorting After . < hc si t orhpsto. Since position.) fourth its in is which i B i − k l i = a = fcrs fe ahrwi sorted is row each after cards, of ) hsals lmn in element smallest th and i  lmnsin elements 1 sthe is , 1 b , 1 . A B o aho hs elements these of each For ) l , 2 i , , eecoe rirrl,this arbitrarily, chosen were b .., ,... = etoe bv,ta are that above, mentioned hr are there 2 i .., ,... hsals lmn in element smallest th nteaoeexample, above the in 3 k n A ilb mle than smaller be will o xml,if example, For . b B ssalrta or than smaller is n i i htaesmaller are that uhta l the all that such lmnsi the in elements = 1 B B , 2 Frthe (For . , .., ,... hc is which B (i.e., A n : i . 129 Solutions .  2 / black n k 1 coins  coins to 2 − n / n n  th square number n prisoners with white hats k one solution for every odd , no prisoner will step forward − 2 1 coins to the row with 1 coin, , n rows with more than 11 > −  n n 2 ≤ / th line up, each of the prisoners who n k k  ≤ rows composing the square in question n black hats since the previous line up did not 2. k coins. This can be done by moving = n n puzzle (#147) in this book. 1 on the other prisoners, then there are exactly black hats, 1 k − , each of the k 2 n 1 line ups. But on the = − k 1) The solution is in the decrease-and-conquer spirit, applied bottom coins. It is natural to create such a square by adjusting the triangle’s − The minimum number of coins that need to be moved is Suppose only one of the hats is black. Then the prisoner wearing it j Hats with Numbers n rows with less than 1 black hats will be able to step forward by the same reasoning as above:  (2 1 2 and three solutions for n − / = ,

j n 1 k  = Since the total number of coins is equal to the Suppose there are two black hats. Then no prisoner steps forward during the first In general, if there are Several versions of this problem have been published both in print and > n hats, one of which is his. At the same time, all the from the longest (i.e., hypotenuse) row with 2 n during the first should—and given their smartness will— stay inthe line color because of their they hats. cannot The deduce smarts can win freedom after all! sees the must have he knows that there arestop the at test. least If he sees Solution The puzzle has two solutions for every even Comments 59. Hats of Two Colors Solution rows by moving the extra coins from the S up by the number of black hats. electronically. This particularW. version Poundstone’s follows, book in [Pou03,spots p. a on 85]. slightly foreheads The different earliest appearedPrinceton wording, logician version around Alonzo Church. of 1935 For a three and more challenging menup, puzzle is see with with the a attributed similar set to the prominent would see only white hats onleast the one other black prisoners. hat, Since it he mustand knows can be make that his. no there Each definite is of conclusion at thewho about sees other the only color prisoners white of sees hats their one is hats. the blackwhich So only brings hat the one the prisoner who freedom steps to forward all during of the them. first line up, line up because none of themthe can second be line certain up about both the prisoners color whosince of see no his one prisoner hat. black stepped But hat forward during during can the stepat first forward. least line Indeed, two up, black they hats. know If that a there prisonersecond sees are black just one hat black is hat, his. he All can concludeabout the that the prisoners the color who of see their two hats and black therefore hats will cannot stay be in certain line. 60. Squaring a Coin Triangle Algorithmic Puzzles 130 u hswudrqiemvn l h on nteee ubrdlns hs total whose lines, to leg. numbered equal even triangle’s the is the in number coins of the one all moving to require parallel would this are But that lines odd-numbered the of composed M FIGURE FIGURE moving then For on,ads na lutae nFgrs43 n .7frteee n d cases odd and even the for 4.37 and 4.36 Figures in of illustrated as on so and coins, ed ob hre n usi noarwta ed ob eghnsle the solves lengthen be to needs that that row row moves. a a of into number from minimum it coin the puts in a problem and takes moves shorten horizontal.) its be being of to hypotenuse each needs the on to that parallel algorithm are any that Obviously, rows coin the and apex the n ut ifrn,slto hw nFgr 4.38. Figure in shown solution different, quite and n oe on,rsetvl.Tesainr on r hw ybakdots. black by shown are coins stationary The respectively. coins, moved and ( n h nycnedrfrasur banbei ee oe ol eteone the be could moves fewer in obtainable square a for contender only The transformation, a such accomplish to needed moves coin of number total The n epciey I hs grs ie ragei hw ihisrgtageas angle right its with shown is triangle given a figures, these (In respectively. , n ,cnb banda follows: as obtained be can ), = 4.37 4.36 M 2 ( , n w ymti ouin for solutions symmetric Two ouinfor Solution however, ) M ¯ n = = ( − n n  )

j n on rmtenx o ih2 with row next the from coins 3  = / = n 2 1 /  (

2 M n j ¯ = n − − S (2) 1 1 − 5 j coins. (2 = = n j / ( − 2 n M  − 1)) 2 (2) = 1) = = n / n S  2 /

1 4 j n = 2 , / > coins. 2  1 n h rbe oshv h third, the have does problem the and  (  n n n − − / + 2  

i n n = and n / / n 2 1 − 2  / (2  2 − on oterwwt 3 with row the to coins 3 )  j = niaecneso added of centers indicate − for 1) n n / > 2  2 n . / 2  . 131 Solutions n 1 is = n + 1 1or k + 4 − n = ... 4. / n + n or 1) 2) , and since either k k 1 is a multiple of 4, − − 4 4 n 1 is a multiple of 4 or n − = ( = n − n n + 1 is a multiple of 4 or n or 1) n − 1) respectively.) The algorithm − , n − 1 n pairs of checkers in consecutive n −  n 2 / , then ( 2) and k 2 n − = n 2 to be even. ( 2 /  / n n coins. 1) 2 1) S − − n 2 is obviously even. n / n 8 checkers from the diagonal to the bottom row one pair at a 2 is even if and only if either pairs in consecutive odd columns—that is, columns 1 and 1) / =  n − n 4 / 1) n n  − An instance of this puzzle by S. Grabarchuk was posted on the n Moving Three solutions for 1. This condition is also sufficient since the problem can be solved by The puzzle has a solution if and only if either is odd, the other must be divisible by 4. Conversely, if either 2; at destination, it is equal to 0. Since any move decreases the sum / n ≥ n 4.39 4.38 k 1) 1or − We can measure the distance between a current position of the checkers and Note that ( Thus, to have a solution, it is necessary that either − is a multiple of 4. The number of moves needed is equal to ( n their destination at the bottom row by the sumAt of the the squares below initial all the position, checkers. this distance is equal to ( there is an even number of odds less than 3, 5 and 7, and so on—down one square. (Note that if n time. where is illustrated in Figures 4.39 and 4.40. n columns—that is, columns 1 and 2,Then 3 move and the 4, and so on—down as far as possible. FIGURE ( Solution Comments FIGURE is a multiple of 4, ( the following algorithm. Move the a multiple of 4. Indeed, if ( exactly by 2, itssolution, parity it is does necessary for not ( change. Therefore, for the problem to have a 61. Checkers on a Diagonal website Puzzles.com [Graba]. Algorithmic Puzzles 132 erae h itnebtenteiiiladfia oiin y2o aho its of each on 2 ( same by the positions makes algorithm final such and any Hence, initial iterations. the between distance the decreases rgamn oslei.Let it. solve to programming neesadteprt eso fteivratie.Bt r icse nthe for in existence solution discussed are Both idea. invariant the techniques. analysis of algorithm on version tutorial parity the and integers a olc n rn otecl ( cell the to bring and collect can tcnrahti elete rmteajcn el( cell adjacent the from either cell this reach can It Comments FIGURE Solution h eto el ntefis oun o uhclsw suethat assume we cells to such cells For adjacent column. no first are the there in and row, cells first of the left in the cells above cells adjacent no are ubro on h oo a rn ocl ( cell to bring can robot the coins of number o 1 for C ruh oteeclsare cells these to brought ubr lsoepsil ona el( cell at coin possible one plus numbers olwn oml for formula following 2 ikn pCoins Up Picking 62. where time. daetcl ( cell adjacent [ i ial,ayagrtmsligtepolm nldn h n ie above, given one the including problem, the solving algorithm any Finally, h uzei eeaiaino rbe 4 n[p0] hc ssaota about asks which [Spi02], in 448 Problem of generalization a is puzzle The C , j [ ≤ i − , c 4.40 j ij j ]= 1 ≤ = ] ssgetdb h itt hspzl,w a s dynamic use can we puzzle, this to hint the by suggested As r qa o0frternnxsetnihos)Teeoe h largest the Therefore, neighbors.) nonexistent their for 0 to equal are Moving m fteei oni el( cell in coin a is there if 1 max h uzeepot h oml o h u ftefis consecutive first the of sum the for formula the exploits puzzle The i and , j { − C C [ n i [ )t h eto t h ags ubro on htcnbe can that coins of number largest The it. of left the to 1) i C n − = , [ 0 = i 1 hcesfo h ignlt h otmrwoepi ta at pair one row bottom the to diagonal the from checkers 9 ]= , C , j 10. [ ] j ] i : , − o 1 for 0 C C 1 [ , [ i i , i j , , ] j j j and )inthe − ≤ ] etelretnme fcisterobot the coins of number largest the be i 1 i , }+ ]} C ≤ j and ) i [ , i n , j tef nohrwrs ehv the have we words, other In itself. ) . i j hrwand row th c − ij i c , ij o 1 for 1 j stemxmmo hs two these of maximum the is ) ] = epciey O ore there course, (Of respectively. , i tews,and otherwise, 0 − ≤ n 1 i − j , hclm fteboard. the of column th ≤ j bv to rmthe from or it above ) 1) n n , / 1 moves. 4 ≤ C [ j i ≤ C − [ m 0 1 , , , j j ]= ] and (1) 0 133 Solutions 6 1 2 4 5 5 5 1 2 3 3 4 4 0 2 3 3 3 values either row 1 is divisible by 4. ] j + , (b)(b) i n 3 0 1 1 2 2 [ C or 6 n 2 0 1 1 1 1 5 table of 1 0 0 0 0 0 m × 4 1 2 3 4 5 n (c)(c) 3 6 2 5 1 4 1 2 3 4 5 (a)(a) 3 The puzzle is an easier version of a problem in [Gin03]. It provides (a) Coins given. (b) Dynamic programming algorithm results. (c) Two The puzzle has a solution if and only if either 2 4.41 1 To get an actual path that yields the maximum number of coins, one needs to Using these formulas, we can fill in the 5 4 3 2 1 by row or columnalgorithms. by This is column, illustrated in as Figure 4.41b it for is the coin typically setup in done Figure 4.41a. in dynamic programming ascertain whether the maximum in equalitythe cell (1) or was the provided one by to the thecell; left value in of above it: the in latter the case, formernot case, it unique, the comes and path either comes from down option the to provides left.Figure that a 4.41c In step shows two case in such some of optimal optimal paths a path. for tie, For the coin an example, setup optimal in Figure path 4.41a. is paths to collect 5 coins, the maximum number of coins possible. Solution Comments FIGURE 63. Pluses and Minuses a nice example of a dynamic programming application. Algorithmic Puzzles 134 nette“ the insert or 1to ett ih rm1to 1 from right to left 4 raigOctagons Creating 64. NP-complete. be to known is problem partition the because exists it for as algorithm known puzzle the for consecutive algorithm efficient the of known no sum is there the integers of sequence for to formula 1 ubiquitous from integers the including themes, several n w onsfis.(oefral,w sueta h onsaesre according first sorted the points Consider are system.) eight points coordinate Cartesian the plane’s the that in assume coordinate first we their formally, (More first. points two Fgr .2)o hyleo ohsdso h ie(iue44b.I h former the In 4.42b). (Figure line the of sides both on lie they or 4.42a) (Figure Solution Comments o3 nette“ the insert 3, to rtadfut ubradmnssbfr h eodadtidnme neach in number third and second groups: the these before of minuses and number fourth and first h n ouin message. solution” “no the ihapu eoete n usto ubr ihamnsbfr hm Since them. before minus a with numbers of subset a numbers S and of them subset before a plus sum: a same the with with subsets elements) common without (i.e., sancsaycniinfrtepzl ohv ouin ssonblw this below, shown As solution. existence. a solution’s have a for to sufficient puzzle also is the condition for condition necessary a as utb qa oeatyoehl of half one exactly to equal be must w ae:ete l h te i points six other the all either cases: two h aeie yfis aigcr ftefis he ubr sfollows: as numbers three first the of care taking first by idea same the utpeo 4, of multiple a utpeo .Ide,if Indeed, 4. of multiple o termidro h iiinof division the of remainder (the 4 mod (1 = h rbe seuvln opartitioning to equivalent is problem The If If osmaie h rbe a esle ytefloigagrtm Compute algorithm. following the by solved be can problem the summarize, To oethat Note n atto Problem Partition + n + (1 n 1 n into sdvsbeb ,w a,freape atto h euneo neesfrom integers of sequence the partition example, for can, we 4, by divisible is 2 + + sod h te utb iiil y4 ovrey feither if Conversely, 4. by divisible be must other the odd, is 1 − − 2 sdvsbeb ,then 4, by divisible is 1 3) 2 +···+ + n easm ihu oso eeaiyta h onsaenumbered are points the that generality of loss without assume We − / p + n n “ and ” ruso orcneuieitgr n hnptpue eoethe before pluses put then and integers consecutive four of groups 4 1 ( hsi nagrtmcvrino elkonpzl,wihexploits which puzzle, well-known a of version algorithmic an is This .., ,... 3 (4 n n ( + + + − n n “ and ” 4) + n 1) 5 n − oevr otcmue cetssbleeta oefficient no that believe scientists computer most Moreover, . − p n t aiy tsol lob oe htfra arbitrary an for that noted be also should It parity. its and = in sidctdb oml 1;i h eane sequal is remainder the if (1); formula by indicated as signs ” / 1) +···+ 8 n see fadol feither if only and if even is 2 6 n n rwtesrih ieconnecting line straight the draw and , n / + ( ( − sovosyeven. obviously is 2 ihte,i n,rsle ynmeigalwro the of lower a numbering by resolved any, if ties, with n n 7) in sidctdb oml 2;ohrie return otherwise, (2); formula by indicated as signs ” + + +···+ 1) 1) (( n / / n 2 ,tesmo h ubr nec ftesubsets the of each in numbers the of sum the 2, = − S = (( hsipisthat implies This . 4 3) k 2 n p k − − 2 − then , .., ,... 3) n 1 ( n n y4.I h eane seult 0, to equal is remainder the If 4). by − = neesfo to 1 from integers − ( n 3 p n 2) ( 7 + n − n i ntesm ieo hsline this of side same the on lie + − 4( samlil f4or 4 of multiple a is 2) 1) ( k − n n − ( − = ( n n ) n ecnexploit can we and 1), 1) + 4 − k p 1) n ic either since and , + 1 1) n and / notodisjoint two into n + utb even be must 2 ) = n p n ) 8 or = 0 hr are There n . n + 0 + . 1isa (2) (1) 1is n 135 Solutions the and 8 P , 2 and 7 8 16 P p p = 1 6 a P consecutive as follows: if in this order, of point sets n , 8 ,... , , an octagon is 1 9 p 8 b p p 5 P . and ,... , (b)(b) 4 10 1 1 P p p convex hulls ... 11 3 P ,... , 1 2 P P lies on the same vertical line as 110 0 , : 9 n 0 p (For example, for the code 01011, b 8 . also serving as one of the octagon’s sides. If the P 0 ... 7 8 ... P p = 2 b 100 1 1 b , b and , 0 6 2 1 P a p , which is used for constructing ... 5 > P 1 , gives the total number of 0’s in the code being identified. Let 4 a 000 lie on both sides of the line connecting 1 P if a (a)(a) 7 ; p 1 quickhull , differ by one, identifying the first bit in the code, 3 The solution exploits the presorting, divide-and-conquer, and 2 P Creating a simple octagon with vertices at eight given points. a = The following sequence of bit strings can be used in 1 ,... , b 2 , and 4.42 2 p 1 a a < be the answer to the second question. Since the bit strings used in the first two Note that all the 1992 remaining points lie either to the right of the constructed 1 2 1 2 P P octagon, or just one leftmost point obtained by connecting consecutive pairs of the points onits or upper above boundary this and line connecting to consecutive form pairs ofline the to points form on its or lower below boundary this (Figure 4.42b). points rightmost point of the constructed pentagon.can Hence, construct an using octagon the with same its method, vertices we at the next eight points a questions to identify a code a with the line connecting it will not intersect with the firsteight octagon. points Repeating on this the step list for solves every the consecutive problem. questions differ only by their firstbits, bits, the corresponding numbers of the correct The first answer, Solution Comments FIGURE case, an octagon can be obtained by connecting the points decrease-and-conquer ideas. It is similarscience to called a well-known algorithm in computer 65. Code Guessing (see, e.g., [Lev06, Section 4.6]). Algorithmic Puzzles 136 oki nte aito nti theme. this on variation another is book The world. the around circles mathematical every for optimal not is It strategy. of decrease-and-conquer value the on based is above Mastermind hno qa o5,since 50, to equal or than an such of applications odd, repeated was from sum 1275. result old with can the starting operation if number odd even be no must therefore sum and new the that implies immediately This Solution 11100 Comments a ote2 ar foe ils1 eo,wihcnb eue oasnl zero Comments single a two to the reduced to operation be the can applying which Finally, numbers, zeros, times. remaining 12 11 operation yields the operation ones the applying Applying of after pairs. pairs above the 24 erasing the while board to the on ones 24 get to yapyn h uzesoeain4 ie.Let times. 49 operation puzzle’s the applying by ntecd eemndb h rtqeto:i hsnme seult h number first the to code’s equal the is number among this zeros if question: of first the by determined code the in next otherwise, hc sod ahoeaino replacing of operation Each odd. is which h oei usin h atbit last The question. in code the 6 eann Number Remaining 66. arbitrary an for needed questions of number minimum oso eeaiy erae h u y2 by sum the decreases generality, of loss prto otepiso h eann osctv integers, consecutive remaining the of pairs the to operation bani ntefis trto ysbrcig1from 1 subtracting by iteration first the on it obtain and hnigadfeetbtoea time. a at one bit different a changing 2 h nta u ftenmeso h or seult 1 to equal is board the on numbers the of sum initial The nfc,oecnsatwt any with start can one fact, In ute,altenmeso h or r lasnneaie hyaeas less also are They nonnegative. always are board the on numbers the all Further, ewl hwnwta n d nee rm1t 9 nlsv,cnb obtained be can inclusive, 49, to 1 from integer odd any that now show will We = b n S ,adtherefore and 1, o nonnegative for , − new 01110 n (2 usin ae tpsil oietf ntr h bits the turn in identify to possible it makes questions 2 . b = o xml,ay5btcd a eietfidb h eune00000 sequence the by identified be can code 5-bit any example, For , n oiieoditgrls hn5 a eobtained. be can 50 than less integer odd positive Any sfo h okb ensSah Sa7.Teslto given solution The [Sha07]. Shasha Dennis by book the from is , n 3) S = , h uzei eso fteprt-ae rbe elkonin well-known problem parity-based the of version a is puzzle The called game board popular the to related closely is which puzzle, The , old 00 p.1516i hsasbo) ognrlfruafrthe for formula general No book). Shasha’s in 105–106 (pp. 00101 (4 0. − , 5) k a b a n 0 and .., ,... − 1 and = b | a +| since 0 , b − ( yields . k a b − n | − n btsrn n aeasqec of sequence a make and string -bit b sawy esta reult h aiu of maximum the to equal or than less always is − 1 n a b k , 1 |= a efudb sn h oa ubro 0’s of number total the using by found be can . is hc r o nw,then known, now are which bits, 1 k > ) , a S a ( : old a 2 k )Rpaigtesm ruetfrthe for argument same the Repeating .) and lssadMinuses and Pluses + − 2 b b , − k by + k k a | a esc ubr ecan We number. a such be + + 3) n − .., ,... .Te ecnapythe apply can we Then 1. b sknown. is b + − | where , 2 a + uze(6)i this in (#63) puzzle = (49 ... b S 3 , old a n .., ,... + 50) usin by questions ≤ − 50 , b 2 = b without a b n . n 1275, − = 1 1; in a , 137 Solutions . ) m n ( S ), the Kvant n 1 ( (#55) in 2, 2 with The sum S − 1; we will n . − 1) 10 − n · n , inclusive, is − , the minimum n 2 such pairs, the n 512 pints. n · / can be decreased / m ( n a 9 S m = 001. , impossible. Hence, the 9 2 m 1, 1 with 10 Odometer Puzzle / 000 a number of times. , − +···+ 1 . n 1 1 − − n − -digit integers, in which each of n pints in it. This is the minimum n n 10 9 10 n . 10 · 2 · 1 · / n − n a n n · = 45 2 10 · 10 = + 45. For each of the 10 possible leftmost digits 6, it is equal to 27 n / which obviously contributes 1 to the sum in 1 1 n , = − 45 − n = n n 10 9 n · = 10 10 n · 2 · ). It is also convenient to pad every integer smaller / n we can get here is equal to n n ) is by pairing 0 with 10 n ( · n S m 9) ( 10 +···+ 1 S · 2 + n + 1 1 − n positive integers.) Since there are obviously 10 = +···+ In particular, for 10 n digits. 2 . · The puzzle is solved by the greedy approach. Its justification is based n 1 (1) n + by an appropriate number of leading zeros so that all the integers are The total digit sum in integers from 1 to 10 Averaging the amount of water in the nonempty vessel successively S · + 1 0 (1 1 − ) is equal to 9 n and our goal is to minimize it.) Since the average of two numbers is always − n 3, and so on, because the sum of the digits in each of these pairs is equal to = n ( a -digit integer, the total sum of the other digits is equal to S − n (The pairing trick was used in the algorithm analysis tutorial to compute the 10 One can also follow an approach used for solving the It is convenient to disregard 10 The third way to solve the problem is to set up a recurrence relation for A simple way to find The puzzle was included, in a different wording, in the exercises to the = n n . n total sum of the digits in them, can therefore be computed as positive amount of waterm among all the vessels in their current state. (Initially, amount of water achievable for that vessel. Indeed, consider by the averaging operation only if this operation involves a vessel containing pints and an empty vessel. After repeating thevessel, averaging no operation empty with vessel each will empty remain, making an increase in ultimate minimal value of the 10 digits occurs the same than 10 sum question, and compute the digit sum in all integers from 1 to 10 greater than or equal to the smaller of the two, the value of denote the latter sum by in a composed of 9 10 45 Obviously, Solution Comments 67. Averaging Down Solution sum of the first this book. Assuming the padding, there are 10 on the monovariant argument, which is discussed in the first tutorial. with each of the nine empty vessels leaves 68. Digit Sum article on monovariants [Kur89, Problem 6],mathematical after olympiad being in 1984. offered at the Leningrad Algorithmic Puzzles 138 h ro ftecniinsnecessity. condition’s the of proof the fte rsre t ftepolmhsaslto,ta s l h hp a be can chips the all is, that solution, a has sector problem two some moving the to hence brought If and one it. parity moving preserves sum’s Indeed, them the changes sectors. of sector neighboring neighboring to a chips to two checker shifting move each after 9 hp nSectors on Chips 69. of application A. an B. is by strategy. approach used decrease-by-one recurrence-based the also The was method 202]. pairing p. The [Kor72, 61–62]. Kordemsky pp. [Mic08, book Michalewicz their M. in and Michalewicz did Z. as invariant an or change representation either osector to olce ntels sector. last the in collected iisi qa o27 to equal is digits Solution Comments analysis algorithm the (see substitutions backward yields tutorial) by recurrence the Solving 10 to equal is digits 45 leftmost the by contributed hp a ebogtt h idesco ie,tesector the (i.e., sector middle the to brought be can chips etr h etrsnme sicue ntesmsvrltmsa well—once as if that times see several to sum easy is the same It in the chip.) included on each is chips for several number are sector’s there sum the (If chips. sector, the the Consider by clockwise. occupied currently say, numbers moving, and sector arbitrary n If 4. of n 1 even of case the consider we because even egbr,toa iei h lcws ieto.(hr sa vnnme of number even an is (There direction. than clockwise less the numbers odd in even-numbered time their a to sectors at odd-numbered two the neighbors, in chips the all hand, moving by other start the on If, sector. middle the oigtgte ahpi fciseudsatfo h ideoeta s the is, one—that middle the and 1 from sectors equidistant from chips chips of pair each together moving ( + samlil f4 e snme l h etr rm1to 1 from sectors the all number us Let 4. of multiple a is n n hs for Thus, e snwpoeta h ttdcniini losfcet If sufficient. also is condition stated the that prove now us Let ewl rtpoeta hscniini eesr o h xsec fasolution. a of existence the for necessary is condition this that prove first will We · + 10 2 sntod ene oso httepolmcnhv ouinol if only solution a have can problem the that show to need we odd, not is +···+ 1) n − n 1 = otesm o h arfo etr4 n oo,utlaltecisare chips the all until on, so and 4, sector from pair the for same the do , hsyed h olwn recurrence: following the yields This . h rbe a ouini n nyif only and if solution a has problem The S n 4 ( arn h ubr ihtesm ii u a econsidered be can sum digit same the with numbers the Pairing n k = S ) n n since and , ( 6 = = n , ) , S 000 10 n = (6) ( S n n 45 , ( n + 001. j n = = and 2 , n (1 − n 1) · 4 45 + 10 i 1) / ≤ )Te ecnmv h aro hp rmsco 2 sector from chips of pair the move can we Then .) utb vna well: as even be must 2 · sodd, is 1 n n + j − 6 − ≤ 1 · 45 . 10 1 n .., ,... ,te ntefia position final the in then ), · 6 n − 10 see,teprt of parity the even, is n 1 n n n = utb iiil y4 hscompletes This 4. by divisible be must − samlil f4 ecn o example, for can, we 4, of multiple a is ec,i h nta oiin h sum the position, initial the in Hence, . j 1 − 27 for and 1 , 000 n n − > , 1 n j 0 n h oa u fthe of sum total the and 000 (0 n + 1 ( sete d ramultiple a or odd either is j n , + —ni h arreaches pair the 1—until = + S (1) 1 (1 1) S + n + / = ean h same the remains trigwt an with starting , 2 2 n S n = 45 +···+ S ) sod l the all odd, is / ftesector the of . = )b simply by 2) 2 k u then But . nj ilbe will 9) = 139 Solutions . , . 3 5 4 9 − = = = k n n n 2 + For coins to the . k 2 6 except + and 3 > 8 , n 2 = , it has several solutions. n 1 , 8 = 5. n = = n n For . and 6 , 0) can be reduced to the instance with two 4 , which reduces the size of the instance by 2. , > k 1)) by moving the coin in position 8 2 2 k − = + k n the puzzle has a solution for every 2( times reduces the instance with , where k 4 + k 2 8 = n + = 8 n = The algorithm above takes advantage of the backtracking and This puzzle, exploiting the notion of parity, is a generalization of n Two possible configurations of the highest and lowest marked cells in the Besides Obviously, the problem cannot be solved for an odd number of coins 4.43 This algorithm obviously makes the minimum number of moves possible Obviously, the puzzle does not have a solution for The oldest reference to this puzzle in David Singmaster’s bibliography [Sin10, because it forms a new pair of coins on each move. instance with 8 coins, whose solution was given above. fewer coins (i.e., Repeating this operation One of them—which can be foundon by 2, backtracking—is then as 1 follows: on 4 3, onthan and 7, 8 5 then (i.e., 6 on 8. Any instance with an even number of coins greater leftmost column with an even number of neighbors for on the last coin in position 8 FIGURE the solution is given in the puzzle’sThis statement. assertion There is can also be no proved solutionfive for by marked contradiction. cells, Assume each that with a athe positive required highest even region in number of of the neighbors, leftmost exists. columnone Consider neighbor of to the the right cells and in one neighbor thiscolumn below of region. it. the The This region lowest cell must cell in have must the one leftmost have neighborThese to two the right possible and configurations one neighbor of above. the marked cells are shown in Figure 4.43. Solution Comments Solution Comments 71. Marking Cells I decrease-and-conquer strategies. Section 5.R.7], is Japanese, datedmany others, 1727. by Ball The and Coxeter puzzle [Bal87, p. haswho 122], called and been it by “one discussed, Martin of Gardner among the [Gar89], oldest and best coin puzzles” (p. 12). 70. Jumping into Pairs I Problem 2 in [Fom96, p. 124]. because in the final state allnumber the even. coins Considering all must possible be moves, it arranged is in notdoes difficult pairs to not making see have that their the a total puzzle solution for Algorithmic Puzzles 140 2 akn el II Cells Marking 72. r loohrsltos st h aeo nodnme fmre egbr,i is it neighbors, marked of puzzle, number next odd the an of of subject case the the of to As values solutions. most other also For are up). bottom applied strategy (decrease-and-conquer daett,sy h ihms eli hsslto—n oiotlyadteother the and horizontally solution—one this in cell rightmost the say, to, adjacent o vr even every For FIGURE this satisfy to is configuration it four-cell and the for neighbors, analysis to similar marked cell A of either. each more requirement number that one requirement even mark the positive to fails a figure impossible have that in must cells cell marked marked five of region the But Solution Comments FIGURE ( atrcnb xeddt ouinfrayodd any for solution a to extended be can latter agrlo ytomre el,a hw nFgr .4 for 4.44c Figure in shown as cells, marked two by loop larger osnthv ouin o hs ausof values these for solutions have not does (c) n h uzei nlddi .A odmk’ atbo Kr5 p 376–377]. pp. [Kor05, book last Kordemsky’s A. B. in included is puzzle The For ouin for Solutions − n = 2) n (a) 4.44 4.45 13. / = n egt3 height and 2 h uzecnb ovdol o nabtayee ubro cells. of number even arbitrary an for only solved be can puzzle The ,teovosslto sdpce nFgr .6.Mrigtocells two Marking 4.46a. Figure in depicted is solution obvious the 2, ouin othe to Solutions ouin othe to Solutions h bv ouin r ae nteiceetlapproach incremental the on based are solutions above The n n = > and 7 6 , , ssoni iue44 for 4.45 Figure in shown as ouini rvddb rm-iergo flength of region frame-like a by provided is solution a n akn el I Cells Marking akn el I Cells Marking = akn el II Cells Marking 1aesoni h iue .4 n .4.The 4.44b. and 4.44a Figures the in shown are 11 (b) uzefor puzzle n n uzefr(a) for puzzle = swell. as (#72). and 6 n > n n = n 1b ipyepnigthe expanding simply by 11 = = and 8 and 8 n hw httepuzzle the that shows 9 = n n = 7 n = , = 13 (c) (b) 10. 10. . n = n 11 there , , and 141 Solutions and , 4 = n ) and squares F (b) j , , F 2 i (c)(c) = n are the row and column of j 4 (Figure 4.46b). Repeating the and = i 6 (Figure 4.46c). In this manner, we puzzle for (a) n . = n 8 chessboard (Figure 4.47a). Under this ’s is clearly based on the incremental n n × (b)(b) : the number of people who have shaken hands at a Marking Cells II ), respectively, where R j , R i ’s is identical to that of the well-known mathematical proposition n The solution for even Solutions to the It is helpful to consider the game’s grid as obtained by connecting (a)(a) Handshaking Lemma ) and ( F 6. 4.46 j , = F i n The puzzle is included in B. A. Kordemsky’s last book [Kor05, pp. 376–377]. Now we will prove that it is impossible to mark an odd number of cells, each If the farmer moves second, he can always push the rooster into a corner to (c) same operation again but markingthe the rightmost vertical cell, neighbor yields below a rather solution than for above approach (decrease-and-conquer strategy applied bottomproof up). for The odd impossibility called the 73. Rooster Chase party with an odd number ofcase, people people shaking must hands be are even marked cells (e.g., sharing [Ros07, edges p. with other 599]). marked In cells. our with an odd number of marked neighbors.following If this contradiction. were On possible, the we would one have hand,for the if each we marked add cell, the we numbercounted should twice. of get On shared an the edges even other hand, number thisnumber since of number each terms must each common be of edge odd which as is is the odd. sum of an odd the squares they occupy. Geometrically, the farmer’s position ( guarantee capture by always movingrooster and to closer a to square him. on Weas will the ( denote same positions diagonal of with the farmer the and the rooster interpretation, the capture can only occur onoccupy the farmer’s two move when adjacent the squares counters (horizontallyopposite colors. or Initially, vertically), the which counters always areboth on have counters the the move squares to of a the same squarecannot happen color. of if Since the the farmer opposite moves color first. on each move, the capture Solution Comments FIGURE vertically (say, up)—yields a solution for can solve the puzzle for any even value of centers of the squares of a standard 8 Algorithmic Puzzles 142 c oiinbfr h atrotrmove. rooster last the before Position (c) ( h amrmkstemv odecrease to move the makes farmer The (8 FIGURE nec oeutlterotri uhdit h pe ih onr(iue4.47c). (Figure corner right side upper its the into of pushed one is rooster along the until shrinks move rectangle each on The 4.47b). (Figure escape cannot rooster oundistance column n h aiu fteetovalues: two these of maximum the find te fe oeb h rooster.) the the by than move larger always a is after distance other row the or distance column the (Either otherwise. o itnebtenhscretsur ( square current his between distance row 1 2 3 4 5 6 7 8 i R , oefra a odtrietefre’ oei ocompute to is move farmer’s the determine to way formal more A , j F 1 F j R ,(8 ), ) 4.47 ; 2 compute , 8) The 3 , ( i F ose Chase Rooster j 4 , R (a) j )fr etnl htcnan h ose n rmwihthe which from and rooster the contains that rectangle a form 8) R − − 1 2 3 4 5 6 7 8 5 j F j F slre hnterwdistance row the than larger is 1 , 6 d h oundsac ewe hs qae;adthen and squares; these between distance column the = 2 7 ae a trigpsto.()Wnigstrategy. Winning (b) position. Starting (a) game. max 3 R 8 { i R (c) 4 − i d i F F 1 2 3 4 5 6 7 8 , 5 , , hti,h oe otergti the if right the to moves he is, that j j F R 1 n h ose’ urn square current rooster’s the and ) 6 − F j 2 F F 7 } . 3 i R 8 R − 4 (b) i F n emvsup moves he and 5 R 6 i R − 7 i F , 8 the 143 Solutions 1 is x for | and x 1 n x − for any x , − 2 2 x 2 belongs to x x x separately. ,... , ) |+| n 1 | and , the sum x x x , it is convenient 1 puzzle discussed n | x | x − − x 1 1 − x − − | n n n x x x ) | and the sum of the vertical )—decreases by 1 after each x |+| |+| F | as the distance between points x j x − x | The sum x 1 − − (and only such value) for which . − − + 2 2 x − 1 |+···+| 2 x n (8 i / x | are the medians of − x n x = ( n | x + y x Chickens in the Corn − n . Since every interval in this sequence is ) + 1 1 F ) x i + | | 2 |+| and x / 2 − . Thus, we have two instances of the same are sorted in nondecreasing order. (If it is not n / x | n x n − y x x n |+···+| x − |+···+| x − and x n x 2 y | − / ( − n |+| ,... , 1 x 1 x 2 x | x x − belongs to each of the intervals with the endpoints at 1 x x |+| | ,... , solves the problem. +···+ x ( 1 1 |+···+| the length of the interval with the endpoints at − y − n , = + 2 1 x 1 / The solution exploits the invariant idea to determine who needs to x − x n | x 1 outside of this interval. This implies that for any even The optimal values for − y and , respectively. | x n 2 ≤ 2 y x be even. Consider first the case of on the real line. We will consider the cases of even and odd x of this interval (including the endpoints), and it is larger than x n x , x n ≤ x 2 To solve the problem of minimizing Let Since the Manhattan distance from the current position of the farmer to the The problem is obviously equivalent to minimizing independently the sum of The problem is a simplification of the and / ,... , n i 1 distances point move of the farmer, after 12 moves the farmershown and the in rooster Figure will be 4.47c, in the from position move. which Thus, at the the farmer longest, it will will catchprovided take the the 14 rooster moves goes rooster first of from on each the piece his starting forthe position next the in rooster Figure game 4.47a. to may Of end, course, hasten theoccupied inevitable by the by rooster getting in as to little a as seven square moves. adjacent to the one y any point problem with different inputs. is minimized when embedded in its predecessor, it is both necessary and sufficient that to assume that the points x upper right corner—computed as (8 the case, we can always sortadvantage of them the geometric first interpretation and of then rename.) It is also useful to take the horizontal distances equal to and Solution Comments the last of them. Inx other words, any value of go first and the greedy strategy for thethe capture grid algorithm. to The the transformation chessboard from may alsorole be here. noted, although it does not play the crucial 74. Site Selection in the book’s second tutorial.collections, for Similar example, puzzles [Gar61, p. has 57] been and [Tan01, included Problem in 29.3]. many puzzle Algorithmic Puzzles 144 rmec vnnmee tto a h egheult hslwrbound: lower this to equal length the has station numbered even each from nnneraigodradtk the take and order nondecreasing in egbrn ttos If stations. neighboring eyipratrl nsaitc.Cmuigtemda fcetyi akcalled task a is efficiently median the the Computing statistics. in role important very h uzet w ntne ftemteaia rbe ffidn idevalue middle a finding of problem mathematical among the of instances two to puzzle the Comments when minimized is and when minimized is FIGURE for tour This Solution h eurmnswl ea es (2 least at be will requirements the 5 a tto Inspections Station Gas 75. and 188–189] pp. [Lev06, 9.3]. example, and 9.2 for Sections [Cor09, see, algorithms, sophisticated more but htsain1hst evstdtieb h uzessaeet h oa number total the statement, 2 puzzle’s least the at by be will twice account visits visited into station be Taking of twice. to least has at 1 stations station intermediate that other the of each visit to otelf fi seult h ubro h ie onst h ih fit. of right the to points given the of number the to equal is it of left the to orwl aet ii station visit to have will tour ovstepolmfreven for problem the solves make 1 Let oeta h idepoint middle the that Note = eeto problem. selection | x ( | x x 2 | n | x x 1 4.48 n − = eod ic h aeof case the Since odd. be 1 1 − ie ubr.Mteaiin alsc au the value a such call Mathematicians numbers. given − − x x ic h rbe eursvstn station visiting requires problem the Since x | 2 1 ouint the to Solution h aeagmnsetnst n d au of value odd any to extends arguments same The . x x |+| ltu osdrtecs of case the consider us —let n |+| |+| h ouintksavnaeo rnfr-n-oqe yreducing by transform-and-conquer of advantage takes solution The = x ssoni iue4.48. Figure in shown is 8 1 x x 2 x x , n 2 − 2 thsasrihfradslto,o ore ottenumbers the sort course: of solution, straightforward a has It = = − − , 3 x 1 n x x x x |+···+| ,  see,tetu htrtrsbc otevstdneighbor visited the to back returns that tour the even, is 2 | |+| n 2 ) a tto Inspections Station Gas eas hsvlemnmzsboth minimizes value this because / , n + 2 3  sa well. as ’s n , , x x ( n 4 h on o hc h ubro h ie points given the of number the which for point the −  3 | x n . , n − / 2 hrfr,tettllnt faytu satisfying tour any of length total the Therefore, 3 tlattiea el ec,i ilas have also will it Hence, well. as twice least at 1 4 2 = n , −  x x —the 4  − |= − stiilt minimize trivial—to is 1 .., ,... x n |+| / 1) x 2  n (  n d |  heeeti h otdls.Frfaster For list. sorted the in element th / x = , x n 2 1 n where  n / 5 |+···+| − rt h sum The first. 3 − − 2 uzefor puzzle 1  x hsals among smallest th 1 − |+| , n d x , | stedsac ewe two between distance the is ) n x +···+| − 3 n 6 n x − n wc,eeylegitimate every twice, 1 = − , x 1 n 8. | | | x ) . n − x 1 : median +| 1 x − x − |+| − x x 7 x x 2 1 |+| | x .., ,... − ene to need we tpasa plays it ;  x n n / x 2 x − |  3 | x x − n | — 8 x | 145 Solutions , n 1 n × − 2 and n n 1. + > n n ,... , 1, vertical moves n + 1 at least three n , n 1 + 2, − n 1 exactly twice. For 1 for any n + − − n n n 1, ,... , 2 among the stations visited 2 + , n + ,... , 1 , n 10 instance of the puzzle. 2 1 moves. Indeed, any such tour will 1 vertical moves needed to switch to = stations, with each of the intermediate n − − 1 moves, which proves optimality of the n is odd, there is no tour satisfying the n n ,... , − n 1 n − n 1 nor station , n + , 1. 1 n 3 is odd. We will show by contradiction that this is − − n n ≥ 2 stations. If such a tour existed, it would have to end 1 horizontal moves needed to switch to another column, 3, it is easy to verify directly that a required tour has to n 1 visited twice. This contradicts the inductive assumption and + − is odd, any tour satisfying the requirements must visit = 1 comprises at least 2 n n − ,... , n n 2 n > 2; otherwise, it would have to visit station , The puzzle is a generalization of Henry Dudeney’s “Stepping Stones” 1 n + The minimum number of moves needed is 2 n board has to make at least 2 ,... , n board is equal to 2 × horizontal moves interspersed with 8 board is shown in Figure 4.49a. The number of moves in such a tour on the n n n An optimal tour can start in the top left corner and, following the greedy Thus, when Let us prove now that any rook tour that passes over all the squares of an Let us prove by induction that if × × the obvious tour intermediate stations at least three times. This implies that for odd values of have to contain moves either along every(If it column does or not along contain every a move row along ofhas some the to column, be board. then passed each over square or of landed that on column along by some a row row, move, then and each if it squareby does of not a contain column that a move.) row move Hence, has such to ainterspersed tour be will passed with have over to contain or either landed on strategy, proceed as far as8 it can before making a turn. The resulting tour for the completes the proof. tour described above. or exactly twice, where board where before this last segment. Butlegitimate then tour this for preceding the segment problem of of visiting the tour would be a the base case of times. Further, the tour would have to end with visit station 2 at leasttour three satisfying times. the For requirements the general that case, visits assume intermediate that stations there 2 is no is optimal. n also the case for requirements that visits intermediate stations 2 another row. This proves that anythe rook tour that passes through all the squares of would have neither station 76. Efficient Rook stations 2 Solution Comments at station in [Dud67, Problem 522], andProblem Sam 88]. Both Loyd’s of “Hod them considered Carrier’s the Problem” in [Loy59, Algorithmic Puzzles 146 xii novospattern: obvious an exhibit 7 erhn o Pattern a for Searching 77. here. difficulty correctness main algorithm’s the the constitutes that of itself proof algorithm a the is than it rather algorithms, greedy with case the often is O ore hsde o rcueapsiiiyta oeptenmyeventually may pattern increases.) 1’s some of that number possibility the as a appear preclude not does this course, (Of Comments FIGURE u fe hti rasdw eas ftedgtcarryovers: digit the of because down breaks it that after But Solution or ssoni iue44b fcus,asmlrtu xsso any on exists tour similar a course, of 4.49b; Figure in shown is board where ouin b natraiesolution. alternative An (b) solution. 1111 h bv ouini o nqe n fatraiesltosfrte8 the for solutions alternative of One unique. not is solution above The h rbe sdsusdi .Gik’s E. in discussed is problem The oee,i h ubr r osdrda binary, as considered are numbers the if However, 1 , 111 × n 4.49 > 1111 , 111 1. ftenmesaecniee sdcml,tefis iepout do products nine first the decimals, as considered are numbers the If oksmnmmmv ah hog h 8 the through paths minimum-move Rook’s h rtslto ie bv sbsdo h reysrtg.A it As strategy. greedy the on based is above given solution first The = , 111 1234321 (a) 1 × ×

11 1 = 1  ... , k 111 1 ,..., , 1  11 , × 111 111111111 × 11 11 , 111  ... k = 1 ahmtc naChessboard a on Mathematics  121 = = 1234567900987654321 × , 11 111111111 111 k  ... − 1 × 1  111 00  ... k = = × 12321 0  12345678987654321 1 or.()Agreedy A (a) board. 8 (b) , , , Gk6 .72]. p. [Gik76, n oon. so and n × n board × . 8 147 Solutions k = 3 n . × where 1 + k 3k3k k 4 square 3 0, we can 2 × + ≥ − 4 k 1 ,  0 1 and therefore = + 1 k n − 2 + ...  k 2 where k 2 k . (b)(b)

= 3 1 100 5 =  0 1 +  = 1 + k 5 1 ... 3, that is,  k k + ...  2 k = 00 > ·  1

n n 2 1 − ...  − 0) is trivial since both of them have a and 2 k k 5  11 2 > 1 and 3k3k 01 2 Indeed, 11 k = k . =  3, that is, = 1 1 ... 2 + 0 > k =  0 4 square in, say, the upper left corner, the 4 2 1) n k k × − − mod 3 ...  ) rectangle (see Figure 4.50a). The 4 k n 1 k 3k3k

3 (2 square with straight trominoes and one monomino. (a) 2 and 100 + n + k = = 2 = × 2 .  1 (4 1 k n 3 k + × ...  + k k mod 3 2 (a)(a) 5 . 11 2 n k The decimal version of the puzzle is from [Ste09, p. 6]. = × 4 Tiling an A tiling in question is always possible. n  1 We can divide the square into three subregions (note the divide-and- k 4.50 ...  . (b) . k 0 11

3 Consider first the case of Similarly, if ≥ + 4 3k3k rectangle, and 3 k requires a monomino placed in one of itsof corners it; to tiling make the it possible other to two tile rectangles the (if rest we obtain tile the board as shown in Figure 4.50b. conquer idea in action!): the 4 side equal to 3 FIGURE 4 Solution Comments Since where we assume that 01 is 1 for 78. Straight Tromino Tiling Algorithmic Puzzles 148 qae n nysc or ilb pnatrtels as h oa ubrof number total The pass. last the after exceeding open not positions be such will doors such only and squares is, eraeb-he taey hr sasml a otl an tile to way simple a is there strategy: decrease-by-three i n nyi ti oge nodnme ftms Door times. of number odd an toggled is it if only and Solution Doors Locker 79. FIGURE Comments Solution Comments where h oiieitgr ewe and 1 between integers positive the iln fa 8 an of tilling npriua,h rvdta h or’ iigi osbei n nyi the if only and if possible 4.51. is Figure in tiling shown positions board’s four the of the one in that placed is proved monomino he particular, [Gol54]. Golomb Solomon In by tiling polyomino on paper seminal the in introduced door i ( 0 h rnesTour Prince’s The 80. Internet. the on and 71–72]) pp. [Gar88b, 141]; Problem [Tri85, (e.g., print Journal for pass n a nodnme fdvsr fadol fi sapretsur,ta is, that square, perfect a is it if only and if divisors of number odd an has = ic l h or r ntal lsd orwl eoe fe h atps if pass last the after open be will door a closed, initially are doors the all Since h rbe ftln h 8 the tiling of problem The i − i 12 = = j i 3) (1 l stgldi qa otenme fisdvsr.Nt htif that Note divisors. its of number the to equal is toggled is , jk 4.51 16 p 3) ic hn tapae nmn te uzecletosbt in both collections puzzle other many in appeared it then, Since 330). (p. sapstv nee.Hne or htaei h oiin htaeperfect are that positions the in are that doors Hence, integer. positive a is uhpisae1ad1,2ad6 n )unless 4) and 3 6, and 2 12, and 1 are pairs such × ≤ then , , ( h ubro pndosatrthe after doors open of number The h uzehsaslto o any for solution a has puzzle The osnthv nte iio ob ace ih.Ti mle that implies This with). matched be to divisor another have not does 4 j orpsil ooiopstos(hw nga)frsrih tromino straight for gray) in (shown positions monomino possible Four n × ≤ − hstln loih a lob osdrda plcto fthe of application an considered be also can algorithm tiling This h uzewspbihdi h pi 93iseo the of issue 1953 April the in published was puzzle The board. 8 k n )sur a led entiled. been already has square 3) fadol if only and if ) divides i o.Hne l h iiosof divisors the all Hence, too. n seulto equal is × j divides hce or ihsrih rmne was trominoes straight with board checker 8  √ n  inclusive. ,  i √ ; n hrfr,tettlnme ftimes of number total the therefore, n .  n hs ubr r h qae of squares the are numbers these : hps is pass th i (1 i i sapretsur (e.g., square perfect a is  a epie eg,for (e.g., paired be can ≤ √ n i × n  ≤ . n n qaeoc an once square j stgldon toggled is ) divides iM Epsilon Mu Pi i i that , = l 2 149 Solutions , 4 1 2. − + n + k k 3 3 = = n board where n , n k 3 and × , = n 1 n + k 1. 3 = = n n , k 3 = n board for 8 board. n 10 board, which was included in a collection of × × × n representing the general cases of , and 8 , 8 board by a prince is shown in Figure 4.52. 7 1. , × 6 > 2. Both solutions can be considered applications of the divide-and- = n Prince’s tour of an Prince’s tour of an 8 + n The problem can be solved by an algorithm asking no more than 3 k 3 4.53 4.52 = 1, and the puzzle also has the trivial solution for n The solution to the puzzle is not unique. Figure 4.53 shows an alternative A tour of an 8 It can be considered composed of three parts: the main diagonal of the board It is easy to see that such a path can be constructed for any The puzzle was motivated by a question about existence of a closed (i.e., re- > questions for solution for n from its lower right tocorner upper to left the end corner, point the thatexactly spiral-like passes once, path through and each from the square the symmetric above upperbelow the spiral-like the left main path main diagonal diagonal. that passes through each square 81. Celebrity Problem Revisited problems for Russian physics and mathematics schools [Dyn71, Problem 139]. Solution Comments FIGURE and FIGURE conquer strategy. entrant) prince tour on a 10 Algorithmic Puzzles 150 s“o”ad“oclbiy tews.I h eert on mn h ru of group the among found celebrity the If otherwise. n celebrity” “no and “no,” is al,weeabokmyhv sfwa n onada ayas many as and coin one as few as have may block a where tails, suehr htteei eert ntegop tl,tesm loihi idea algorithmic same the Still, group. the If in follows. as celebrity works a is there that here assume ys”ad“oclbiy otherwise. celebrity” “no and “yes,” os aeis case worst 2 ed Up Heads 82. [Kin82] above. Smith-Thomas described and algorithm King the by computer improves paper further a that to its pointed origin also and problem’s and the Aanderaa algorithm traced O. S. He to the 5.5]. Section discussed [Man89, book Manber his in implementation Udi solving. problem one h oml o h eei emo h rtmtclporsin h ouinis solution The using progression. by arithmetical or the of substitutions, term Q backward generic substitutions, the for forward formula by the solved be can It A if the for celebrity; recursively a problem B. the be Solve knows can group. of A who this group remaining whether from people B A remaining remove ask the B, know from and not A B, does remove and B, A knows say, A group, If the from people two select i ieo lentn al n ed htsat ihati) nagrtmthat algorithm An tail). a with starts that heads and tails alternating of line a (in Solution Comments niae htteei oclbiyaogtegopof group the among celebrity no is there that indicates ie htnme a ea ml szr i ieo l ed)ada large initial as the and heads) in all blocks of tail line a of (in number zero as the small as as large be may as the number least That to line. at get be to needed the must all moves blocks flips of tail also number zero block the such Therefore, one them. than between more blocks flipping head since 1 tail than of more number no the decrease by can blocks coins successive of number any Flipping type. same sa follows: as is of eert,ad“oclbiy tews.I h eert on mn h ru of group the among a found as celebrity C return the n “yes,” If is otherwise. question celebrity” second the “no the after and to after removed celebrity, answer person removed the the person If whether the C. “no,” knows knows is question C answer first whether the person if a ask and, is C, question celebrity say, first identified B, the the or If A celebrity. either a than be other to not known is question first − − ( n nietesmlrvrindsusdi h oksfis uoil ecannot we tutorial, first book’s the in discussed version simpler the Unlike h eurnefor recurrence The ecntiko h onln scmoe fatraigbok fhasand heads of blocks alternating of composed as line coin the of think can We n epecno oti eert ihrbcuetepro eoe fe the after removed person the because either celebrity a contain cannot people epei ,js s hte nw :rtr saclbiyi h answer the if celebrity a as B return A: knows B whether ask just B, is people 1 ) epei ,akwehrBkosA eunAa eert ftease is answer the if celebrity a as A return A: knows B whether ask A, is people 1 = Q 2 ( + n h iiu ubro oe eddt ov h uzei the in puzzle the solve to needed moves of number minimum The )  3( n h loih rvdsa xeln xml fdecrease-by- of example excellent an provides algorithm The = / n 2 Q  − . ( n n n 2) − = − Q epewocnsilb eert.I h ouinreturned solution the If celebrity. a be still can who people 1 = 1 1) ( , n 3 h n esni eert ytedfiiin If definition. the by celebrity a is person one the ,tenme fqetosnee ntewrtcase, worst the in needed questions of number the ), n + − for 3 for 4 n n > > and 1 2 , Q Q (1) (2) n − = = epe h agrgroup larger the people, 1 0. 2 , Q (1) n = on fthe of coins 0 . n  > n / 2 1  , 151 Solutions  2 1. / n . −  1 n − n 3 = . 2 2 + = 1) (1) − )is M n 1 ( − n , M 1 3(3 do the following: > , = n 1 ) 2 n > ( 1 for the solution, which can be verified + n − 1 disks from the source peg to the 1) 2 for n − − + nM 12 326 3 28 480 n n ( = 1) ) 1 disks from the destination peg to the source 1 disks from the source peg to the destination M − n ( n − − article on monovariants [Kur89]. As the monovariant, ( ) are given in the following table:. M n n n M ( 3 M = Kvant ) 1 and 3 n ( − n M The algorithm suggested above can be considered an application of 3 move the single disk from the source peg first to the middle peg and The minimum number of moves needed to solve the puzzle is 3 HT line was also included in [Fom96, p. 194, Problem 90]. , = 1 ) n ... = ( destination peg through the middle peg. peg through the middle peg. peg through the middle peg. n M If The recurrence relation for the number of moves • Move the bottom• disk from the source Transfer peg recursively to the middle peg. • Move the disk• from the middle peg Transfer to recursively the destination peg. • Transfer recursively the top by the substitution into the recurrence: then from there to the destination peg. If Alternatively, the recurrence can besubstitutions solved explained, by for example, the in standard [Lev06, Section method 2.4]. of backward The first few values of The algorithm is illustrated in Figure 4.54. Solution Comments solves the puzzle in thein minimum the number first of tail moves block caniterations simply in in the flip the worst all case. current the line coins until no tails are left; it will need They suggest the formula 83. Restricted Tower of Hanoi the decrease-by-one strategy. This puzzle wasD. also B. used Fomin by in L. their D. Kurlandchik and they considered the number ofchange TH by and more HT than pairs two inthe on the HT any coin move. line, The which 100-coin cannot instance of this puzzle for Algorithmic Puzzles 152 FIGURE 4.54 eusv loih o the for algorithm Recursive etitdTwro Hanoi of Tower Restricted puzzle. 153 Solutions , 1 − 1 + n 2 is the number 3 ≥ = 1 moves. The above n 1. 1) − 1 disk moves to transfer that is, until the problem − n − , n puzzle allows direct moves − n 1 . n (3 1 − 1 disks. Before the largest disk n + ≥ + 1 1 disk moves. Moving the largest 3 flips where n = n + k − − 1 disks from the left peg to the right n n 1) 1 holds. Assume now that the inequality − 1 for n − Tower of Hanoi − smaller disks must be in a tower on the left − n puzzle was mentioned in the 1944 paper by 1 n n 3 (3 3 ≥ + ≥ ) be the number of disk moves made by some 1 n ) ( n (1) ( + A A A 1 more disk moves yet again. To summarize, the total , 1) 1 − − = n Tower of Hanoi n n smaller disks must be in a tower on the destination peg. By the (3 n ≥ the number of pancakes at the bottom of the stack that are in their 1 disks and consider the case of The classic version of the 1) , k ≥ The problem can be solved in 2 + n n ( A The decrease-and-conquer strategy leads to the following outline of an Initialize This version of the It is not difficult to prove that the above algorithm solves the problem in the As far as the underlying design strategy is concerned, the algorithm is definitely can be moved, all inductive assumption, it requires at least 3 holds for peg requires at least 3 disk to the middle pegbe takes moved at on least the destination one peg, move. all Then before the largest disk can them there. Moving the largest diskat from least the middle one peg move, to and the transferring right the peg requires algorithm. Repeat the following step untilpancake the not problem yet is in solved: its bring final theto position largest its to the final top position with with one onethis flip, more outline. and flip. then Here take is it a down more detailed implementation of of pancakes given. between the left andpossible right to pegs; solve the as puzzle shown in the in minimum number the of second 2 tutorial, this makes it number of moves made by the algorithm must satisfy the inequality fewest moves possible. Let algorithm solving the puzzle. We will prove by induction that based on the decrease-by-one approach,strategy, it but solves three unlike rather the than two standard instances of version size of this algorithm solves the puzzle in thethe maximum same number configuration of of the moves disks that (see thefrom do “Tower [Bogom]). not of repeat Hanoi, the Hard Way” page peg; by the inductive assumption, it requires at least 3 Solution which completes the proof. Comments For the basis case of final positions to 0. Repeat the following until 84. Pancake Sorting R. S. Scorer et al. [Sco44]. Algorithmic Puzzles 154 fti ags ack snto h o ftesak ld h ptl ne tand it under spatula ( the the slide with Starting stack, top. the the of on top it put the solved.) to on flip is not problem is the pancake pancake, such largest no this is If there (If it. below immediately one the iue4.55. Figure by least at place final of their value in the pancakes update of Finally, number one. the increase to flip and pancake h olwn xlctfruafrits for formula explicit following the yacntn o yacntn atr ti o pia,hwvr h minimum The (15 however. between optimal, lies case not worst is the It in needed neither factor. flips constant is, of number a that by irregularly, nor decreases constant size a by problem’s the where strategy, conquer h otmo h tc,weei osntpriiaei n ute is Hence, of flips. stack further any any for W in needed participate flips of not number does total it the where stack, the of bottom the h nta condition initial The where the above pancake largest the Find solved. is Comments enslce stelretoto-re ack. ld h ptl ne the under spatula the Slide pancake.) out-of-order largest the as selected been the netapnaelre hnalteohr ih eo h o ack.O the the flipping On to pancake. problem the top reduce the to of below flips stack two worst-case right make others will algorithm the the all stack, new than larger pancake a insert h tc pt n h rtpnaeta ssalrta h o ack.Lti be it Let pancake. top the than smaller is that pancake the first the find to up stack the osrce sflos lpawrtcs tc of stack worst-case a Flip follows. as constructed tm rmtefloigrcrec relation: recurrence following the from stems h agro h w acksi ntebto.Cnie nabtaysakof stack if arbitrary flips an no Consider makes bottom. it and the top on the is on pancakes is n two pancakes the two of the of larger larger the the if flip one in uze tmnin,i atclr htteol eerhpprpbihdby published paper research only problem. the this to this devoted that was about Gates particular, facts Bill founder interesting in Microsoft’s few mentions, a there It find puzzle. also can One [Bogom]. Bogomolny the of page known. not is value exact > ( h ubro ismd yti loih ntewrtcs is case worst the in in algorithm shown this by is made flips 2.20 of Figure number The in instance the on algorithm the of iteration first The ic h bv eurnerlto ensa rtmtclporsin eget we progression, arithmetical an defines relation recurrence above the Since hr savsaiainape ftepzl nte“lpigpancakes” “Flipping the on puzzle the of applet visualization a is There n j j hpnaefo h otm Nt htaltepnae rmte( the from pancakes the all that (Note bottom. the from pancake th h nlsv,aei rprodrbcuetepnaecretya h o has top the at currently pancake the because order proper in are inclusive, th, acks ihtoflp rls,teagrtmpt h ags ack at pancake largest the puts algorithm the less, or flips two With pancakes. 2 − n 1) ≥ + stenme fpnae.(Obviously, pancakes. of number the is 2 neatv ahmtc iclayadPuzzles and Miscellany Mathematics Interactive h bv loih sa xeln xml ftedecrease-and- the of example excellent an is algorithm above The 2 W . nfc,ti pe on satie ntesakof stack the on attained is bound upper this fact, In ( W n n ) ( − n = W ) pancakes. 1 (2) W = ( 1 n = + − stu eas h loih ovsteproblem the solves algorithm the because true is 1 2( k 1) yrpaigi by it replacing by n + − n helement: th for 2 2) = k + k 2 hfo h otmta slre than larger is that bottom the from th n n )hpnaefo h otm scan bottom, the from pancake 1)th > − n n for 3 2 − acksi one bv by above bounded is pancakes j , . acksusd onand down upside pancakes 1 W W / n (1) 14) (2) ≥ est yAlexander by website n = 2 = n (5 and . W . hsformula This 0.) 1 . ( n ) / k n 3) = + pancakes n 2 u its but , )hto 1)th n − j 3 th , 155 Solutions 1 persons. − n 2. − algorithm. n Pancake Sorting Two flips of the first iteration of the The minimum number of messages is equal to 2 4.55 There are several ways to do this. For example, they can designate one person, say, person 1, to whomknow. After everybody receiving all else these messages, sends person 1 theor combines her message all rumor the and with rumors send with the this his combined rumor message to they each of the other Solution 85. Rumor Spreading I FIGURE Algorithmic Puzzles 156 hc ek oices smc spsil h oa ubro nw rumors known to of 1 number from total persons the the Number possible sent. as message each much after as increase to seeks which otmu yepnigaslto for solution a expanding by up bottom II Spreading Rumor 86. great of obviously networks. are communication puzzle with dealing this specialists to to similar importance Problems 3]. Problem [Ton89, 1971 es w xr esgs oadfo h xr esneatywa h above the what at person—exactly requires extra one the by from persons provide. and of algorithms to number messages: the extra of two increase an least that fact the from stems Solution Comments Comments FIGURE ovrain r edd o xml,P example, for needed: are conversations oa ubro ovrain nti loih seult 2( to equal is algorithm this in conversations of number total where 1 n epcieyaeovos eei n fsvrlagrtm htaheethe achieve that algorithms 2 several with of goal one puzzle’s is Here obvious. respectively—are fprosP persons of P esgsa olw:fo o2 rm2t ,ads n ni h message the until on, so and 3, to 2 12 from persons to 2, known to initially rumors 1 the combining from follows: as messages P P eunilodro ovrain sidctdb h aeso h de connecting edges the on labels the by parties. conversing indicated the representing is vertices the conversations of order sequential . , 6 4 2 ,... 2 ,P h aenme fmsae srqie ytefloigged algorithm, greedy following the by required is messages of number same The h atta 2 that fact The hnsn h esg obnn l the all combining message the send Then ihP with .., ,... 1 n ihP with ,P 4.56 ≥ 3 n n P P For . 4. For o h eodtm.Teagrtmi lutae nFgr .6 The 4.56. Figure in illustrated is algorithm The time. second the for pia uo pedn i iaea ovrain for conversations bilateral via spreading rumor Optimal − 6 5 5 4 ,P h loih ie bv xlistedces-n-oqe idea decrease-and-conquer the exploits above given algorithm The in olympiad mathematical Canadian a at offered was puzzle The 1. n n P and n 6 n = ,... > − 1 , 2 esgsi h mletnme eddt ov h puzzle the solve to needed number smallest the is messages 2 4 n 2 2 1 8 7 ,P , ihP with , − h ouinfor solution the n 3 and n ovrain o any for conversations 4 akwt esnP person with talk 3 , n hnmkn P making then and h ouin—eurn ,1 n conversations, 3 and 1, 0, solutions—requiring the P n 1 = n 1 = ihP with .Atog ti o ifiutt devise to difficult not is it Although 4. 3 5 n a eetne ymkn each making by extended be can 4 1 uosfo person from rumors eoeP before 2 1 ,P .., ,... akwt aho esn P persons of each with talk P P n 3 2 4 n ihP with ≥ 1 n edtefirst the send and n ak ihP with talks .For 4. n − − 4 6 4 ssn operson to sent is 1 ,P 4) 1 + P n ihP with 3 n 4 n = opersons to 2 = = ,P 4 2 , 3 :the 6: 4 n n and , with four − − 5 4 1 , 157 Solutions 1) + times: n [Tri85, n ( 000000 n 1 cells to 1) cells to → + (We assume + . 0 n n n ( n 6. The upside down 11111 ,... , 2 = 1 cells to end up in cell → , n 1 1 + 1 n is even, the problem can be = 4. For a proof, see the article i Mathematical Quickies n ≥ 0000 if n ; 4 conversations, it is much harder n → − n 00 Frogs to pass each other. Further, since .) 0 n n 111 th glass, where i → Toads and 111 1 n 00 moves. n the second Toad has to move → , 1, the number of glasses turned over in one move, is even. 2 − + 0000 n n 0 The puzzle is one of several versions of the well-known problem in 1 We can find the number of slides and jumps in an algorithm solving There is no solution for any odd moves, which is the fewest number of moves required. n → and so on. Added together, all the Toads have to move is odd, is even, the problem can be solved by making the following move , n n 3 jumps are necessary for Since any two consecutive moves will either have no impact on the state of Here is an example of the algorithm’s application for If If The puzzle was included by Charles Trigg in his 11111 + 2 1 their final positions. By the similar reasoning, the Frogs have to move glasses are denoted by 1’s, theover others on are the denoted next by move 0’s; is shown a in glass bold. that is not turned the glasses or change the stateproblem of in fewer exactly than two of them, no algorithm can solve the end up in cell that the glasses are numbered from 1 to solved in 87. Upside Down Glasses by C. A. J. Hurkens [Hur00],further references. which D. also Niederman gives contains another algorithm the for above the[Nie01, puzzle algorithm Problem in and his 55], book some prefacing the“is puzzle’s destined to statement become by a classic.” saying that the puzzle Therefore, the parity of theremain odd, number as of it glasses was in thatnumber the are of initial upside upside position. down Hence, glasses down is the will 0, final which always position is in even, cannot which be the reached. turn over all the glasses except the Toads cannot jump over each other, the first Toad has to move n to prove that this number is the minimum for Solution Comments Solution an algorithm that solves the puzzle with 2 88. Toads and Frogs Problem 22]. which some objects can be infrom one one of two state states to andproblem the the can goal other. be is solved, Their to the decrease-and-conquer transform solutions strategy. them often exploit parity and, when the the puzzle as follows. The onlya way jump. a (Which Toad and of a the Frog creaturesn can jumps pass over each which other does is not with matter here.) Hence, Algorithmic Puzzles 158 epciey up nfc,i lasuiul end n hrfr osnot does therefore and defined, uniquely indicator. always subscript is a require fact, in jump, A respectively. el oterfia oiin swl.Addtgte,altecetrshv omove to have creatures the all together, Added 2 well. as positions final their to cells olf.Temvsi h etpr ftesrn lf rmtevria ie make line) vertical the from (left TFTF right string the and the in right of alternate to part left Frogs left same and the the Toads in reads moves it is, The that left. palindrome, to a is string above The made: moves the indicating letters FIGURE ihtesbcit lentn ewe Ta’ ld)adF(rgsslide), (Frog’s F and slide) of (Toad’s groups with T interposed are between which alternating subscripts the with etpr efre nrvreorder. reverse in performed part left upwietesubscripts the made. while being moves jump the a and states board’s the show n odd and even for cell empty the hiebtenasieadajm,tejm utb ae h loih is algorithm The made. be must for jump a 4.58 the Figure is and jump, there 4.57 Figure a whenever in and particular, illustrated slide In the a ends. because between dead defined obvious choice uniquely to are lead moves moves obtained its be alternative can thinking: algorithm brute-force The one. Without essentially former Frog. the first by the describe of will slide we the generality, with of starting other loss the and Toad last the of slide ubro ldsi qa o2 to equal is slides of number opsdof composed n − ( ngnrl h loih a edsrbdb h olwn tigo 2 of string following the by described be can algorithm the general, In hr r w ymti loihsfrsligtepzl:oesatn ihthe with starting one puzzle: the solving for algorithms symmetric two are There n 1 + . h eta ato h tigtasom h atr noFTFT into pattern the transforms string the of part central The 4.57 )cls ic n upcvr w el,adteeare there and cells, two covers jump one Since cells. 1) ouint the to Solution nJ S T s h ih ato h tigfiihstets ytemvso the of moves the by task the finishes string the of part right The ’s. JS F JJ ... od n Frogs and Toads SJ n  T ( n ... n − and + 1 n s epciey ti opsdof composed is It respectively. ’s, J 1) S J s(up)woenme nrae rm1to 1 from increases number whose (jumps) ’s F | − J niaeamv yaTa n Frog, a and Toad a by move a indicate ...  ... n 2 uzefor puzzle n  2 J Fpten olwdo rcddby preceded or followed pattern, TF | n = SJ =

2 n ...  n and 2 − . n 1  J = S ... and 2. n = JJS J 3 niaeasieand slide a indicate , F epciey They respectively. JS n T 2 nS fte,the them, of ... s(slides) ’s T tis it FT; n + n 2 159 Solutions n Toads of which 2) moves. , , see David jumps and n + Toads and 2 n + n m m Toads and Frogs 1)( + + n mn ( 2) times: once for each n + 3. n = Hares and Tortoises n and puzzle for 2) slides, for the total of 2 Sheep and Goats 1 cells, the two-dimensional algorithm will make + + n n Toads and Frogs (2 are slides. In other variations of the puzzle, the number of n n + m The puzzle can be easily generalized to the one with Solution to the The puzzle is a two-dimensional version of the puzzle will have to be applied the total of (2 2) jumps and 2 4.58 + n are jumps and slides on a line with 2 Ball and Coxeter [Bal87, p. 124] reference the book by Lucas [Luc83, (2 n 2 mn 2 pp. 141–143] as the puzzle’salternative names source. have included For other references to this puzzle, whose empty cells separating Toads from Frogs may be greater than 1. puzzle (#88). It canmiddle be column. solved Whenever by this applying algorithm createsfor the the a algorithm first vacant time, for we cell can that in switch thethe puzzle to exchanging board’s same to the row algorithm. counters the in Thus, that row theand by Frogs algorithm applying for solving the one-dimensional row and once for the central column. Since that algorithm makes Solution Comments FIGURE n 89. Counter Exchange Singmaster’s annotated bibliography [Sin10, sec.website 5.R.2]. Alexander [Bogom] Bogomolny’s providesdiscussion a of its good solution on visualizationpage. the applet “Toads and of Frogs puzzle: the theory puzzle and solution” and a Frogs. Then the total number of moves required is equal to Algorithmic Puzzles 160 etn,tepolmi eue ognrtn l emttoso 1 of permutations all generating to reduced is problem the seating, 0 etn Rearrangements Seating 90. page. “Toads dimensions” its two on in puzzle puzzle this Frogs for section and applet Bogomolny’s Toads” visualization Alexander good and a [Sin10]. provides “Frogs [Bogom] bibliography the website annotated see Singmaster’s references, David other For in source. puzzle’s the as one- its to problem a a possible. such always of not course, is Of version reduction method. problem-solving two-dimensional common a a is counterpart of dimensional reduction a general, In osleteaau rbe Se4 rbe 8.Tepolmo generating of problem The 98]. Problem [Ste64, Steinhaus the Hugo problem 74], mathematician abacus Polish p. the the [Gar88b, solve by Gardner to discovered computer Martin fact, in to in was, According known algorithm 1962. is around it algorithm independently published who this researchers two after of algorithm, Johnson-Trotter the version as science nonrecursive The strategy. Solution Comments Comments FIGURE rnpsn w daeteeet.Teepruain a eotie yfirst 1 by of obtained be permutations can all permutations generating These elements. adjacent two transposing emtto f1 of permutation prahbto pfor up bottom approach noalpsil oiin nec emtto f1 of permutation each in positions possible all into hteeypi fcneuiepruain ifr nyb rnpsto ftwo of transposition by insert only to have differs we permutations elements, adjacent consecutive of pair every that rrgtt et ttrsotta ti eeca osatwt inserting with start to beneficial is it that out turns It 12 left. to right or aladCxtr[a8,p 2]rfrnetebo yLcs[u8,p 144] p. [Luc83, Lucas by book the reference 125] p. [Bal87, Coxeter and Ball ecninsert can We ... ( 4.59 n − fe ubrn h hlrnfo to 1 from children the numbering After )b oigrgtt etadte wthdrcineeytm new a time every direction switch then and left to right moving by 1) eeaigpruain otmup. bottom permutations Generating h ouini lal ae ntetasomadcnurstrategy. transform-and-conquer the on based clearly is solution The h loih sapretilsrto ftedecrease-by-one the of illustration perfect a is algorithm The , n 2 notepeiul eeae emttosete ett right to left either permutations generated previously the into .., ,... n n ≤ − sgvni iue4.59. Figure in given is 4 ed ob rcse.A xml fapyn this applying of example An processed. be to needs 1 , 2 .., ,... n nteatraigdirections. alternating the in n − eusvl n hninserting then and recursively 1 , 2 n .., ,... nteodro hi initial their of order the in n − .T aesure make To 1. , 2 .., ,... n n into by n 161 Solutions 2 2 m × 2 is odd vertical 2 2 t k 2 squares m × squares of each is odd, no tiling 2 m m where is divisible by 4. m horizontal tiles and n 2 squares of one color and 2 t 2 = m n is even but not divisible by 4. n cells with the board can be divided into 4 2 , m k 4 4 = = squares of each color to be covered by horizontal board where 2 after the paper by D. H. Lehmer [Leh65], who n 2 n n m × n board has an odd number of squares. Therefore, no domino The colored board has 2 n . is an even number, one can tile one half of the 2 2 × 2 m n k The solution is typical for tiling puzzles. When it is possible, a tiling = board with an equal number of horizontal and vertical dominoes is t Coloring of an A required tiling is possible if and only if n × 4.60 is even but not divisible by 4, that is, is divisible by 4, that is, is odd, the Lehmer’s Motel Problem n n n n If If If tiles, where with horizontal dominoes anddesired tiling. the other half with vertical dominoes to get a color, leaving the remaining whereas the number of squares covered by dominoes must be even. tiling of such a board is possible, becauseof any squares. domino tiling covers an even number of an dominoes. But this is impossible for either of the two colors because squares. Since 4 Comments FIGURE squares of the other color. The vertical dominoes would cover 91. Horizontal and Vertical Dominoes Solution considered a more generaldistinct. problem of permuting numbers that may not all be permutations by transposition of adjacent elementsto has as sometimes been referred possible. To prove this, we color theFigure board’s 4.60 for rows an with example). two Note alternating that colors anyof (see horizontal the tile same would color, cover and two any squares verticalWe tile want would to cover cover two squares the of board’s different colors. is obtained by partitioning the boardimpossible, into an regions invariant that argument are is easycoloring. used, to Such often tile. When based examples it on are is techniques. either given parity in or board the book’s tutorial on algorithm analysis Algorithmic Puzzles 162 2 rpzi Tiling Trapezoid 92. Engel’s ein(iue46) egttefloigformula: following the get we 4.61), (Figure region ieadteeultrltinl bv h ie h omrcnb isce into dissected be can former The line. the above ( triangle equilateral the and line FIGURE Solution osdrteln aallt h aetruhtepit iiigtergo’ sides region’s the dividing points the through 3 base the to parallel line the Consider and triangles, small three of up made is tile trapezoid one Since iigeitne e spoeta if that prove us let existence, tiling fataeodtln xssfor exists tiling trapezoid a if h ein tcnb ie ytaeod.Ti ses opoeb nuto on induction by prove to easy is This trapezoids. by tiled be can it region, the y3fratln oeit But exist. to tiling a for 3 by ,wihimdaeyi salse ycnieigtecssof cases the considering by established is immediately which 3, k ie;telte a etldb h nutv assumption. inductive the by tiled be can latter the tiles; t oms qiaea ragecopdof fe lcn 2 placing After off. chopped triangle equilateral topmost its n ftesdso h ein(e iue46afra xml) ewl eleft be 3 size will side we of example), triangle an equilateral for whole 4.63a the Figure tiling of (see task region the the with of sides the of one k = : hstln uzei elkon e,freape iia rbe nArthur in problem similar a example, for see, well-known: is puzzle tiling This onigtesaltinlsb h aessatn ihtebs ftetriangular the of base the with starting layers the by triangles small the Counting eoew hwta hscniini o nyncsaybtas ufiin o a for sufficient also but necessary only not is condition this that show we Before o osdrtecs fa qiaea rageo iesize side of triangle equilateral an of case the consider Now + 3 n 1 k 1) , = Fgr .2) hsln iscstergo notetaeodblwthis below trapezoid the into region the dissects line This 4.62b). (Figure h eincnb ie ytretaeod Fgr .2) e spoethat prove us Let 4.62a). (Figure trapezoids three by tiled be can region the 4.61 rbe-ovn Strategies Problem-Solving + 3 k k h uzehsaslto fadol if only and if solution a has puzzle The + eint iewt rpzi ie i ry for gray) (in tiles trapezoid with tile to Region qiaea rage fsd ie3adhnecnb ie ytrapezoid by tiled be can hence and 3 size side of triangles equilateral T 2. ( n ) = =[ n n + + 2( 2( n n 2 n n = − − − 3 sdvsbeb fadol if only and if 3 by divisible is 1 1) Eg9 .2,Polm9]. Problem 26, p. [Eng99, 1) k n n where / + = 2 2( − 3 k n k 1 n osaltinl srmvdfrom removed is triangle small no and − ≥ = 2) 1 n , 2 +···+ ti loeit for exists also is it n − sntdvsbeb 3. by divisible not is 1 . n = n 2 2 6. · − n 1 k n ]− utb divisible be must 1 = n sntdvsbeby divisible not is rpzisalong trapezoids k 3 = , n 1 k hc a be can which , = 3 n k = 3( + 3 k with 1 k k + . + For 1) 1 , . 163 Solutions 8. = n 3. (b) Recursive = n 1 trapezoids along the 7 and (b) (b)(b) + = 1 (see Figure 4.63b for an k n + k 3 (b)(b) = 1. n > k we can place 2 the region is congruent to one trapezoid , , k , 2 3 2 + = = the puzzle can also be solved by the following k n , n 3 k 2 = = n place the longer base of the first tile in the middle of the n , 1 > k (a)(a) The above solution takes advantage of the invariant, decrease-and- where First step in tiling the triangular region for (a) (a) Trapezoid tiling of the whole triangular region for k 2 (a)(a) = 4.63 4.62 n It is interesting that for tiling of a whole triangular region for divide-and-conquer algorithm. If region’s base to reduce this instance to that of example). regions’s base. Then draw three straightthree lines sides connecting of the the middle triangle from points which of theregion the region into was four obtained. congruent subregions This similar will to dissect the the original region but exactly half FIGURE Comments done as shown above. And if FIGURE tile. If conquer, and transform-and-conquer ideas. Algorithmic Puzzles 164 a4 (a FIGURE for 4.64b Figure that in algorithm, illustrated same is the algorithm by The tiled recursively. be is, can them of each Hence, 4.64a). (Figure size its FIGURE Solution iue4.65. Figure b lutaino h iieadcnurtln for tiling divide-and-conquer the of Illustration (b) icse ntebo’ rttutorial. first book’s the in discussed 3 itn Battleship a Hitting 93. of University the at solving problem algorithmic on [Backh]. Nottingham course his in Backhouse iia oteagrtmfrtoiotln 2 a tiling tromino for algorithm the to similar h uzesisac for instance puzzle’s The × 4.64 4.65 1or1 h iiu ubro ht eddt urne itn battleship a hitting guarantee to needed shots of number minimum The a iscino h raglrrgo nofu iia ein aftesize. the half regions similar four into region triangular the of Dissection (a) ouint the to solution A × (a) etnl)i 4 n ftepsil ouin ssonin shown is solutions possible the of one 24; is rectangle) 4 itn Battleship a Hitting n = 2 k a sda nidcineecs yRoland by exercise induction an as used was n puzzle. × n = 2 n 8. einwt isn square missing a with region (b) n = 8 . ti obviously is It 165 Solutions [Gik80] gave another puzzle. Kvant 8 board, for which the minimum of × Hitting a Battleship The puzzle illustrates the idea of the worst-case analysis in a rather Alternative solution to the Twenty-four possible positions of the battleship. Let us start by turning up the card at the upper right corner of the array 4.67 4.66 The answer to the same question for an 8 The fact that less than 24 shots are not going to do the job follows from 94. Searching a Sorted Table 21 shots are needed, was givenhis book earlier on by polyominoes Solomon [Gol94]. Golomb in the first edition of Figure 4.66, which shows 24being necessary possible to hit positions each of of them. the battleship, with one shot Solution FIGURE Comments FIGURE unusual setting. An article in the Russian journal 24-shot solution, shown in Figure 4.67. and compare its number with the number we are searching for. If the numbers are Algorithmic Puzzles 166  5 a-i Weights Max-Min 95. 9.6]). Problem [Laa10, (e.g., interviews technical to devoted publications of number the number. or search rows the of contain number may that the columns either decreases it iteration each on because eve on.If coins. heavier Solution Comments and horizontal nine than more have cannot cards. segments. 19 it vertical of nine because total longer, the be up can turning line corner, array. such left the lower No in the card at some ends to line corner such right longest upper The the from down or left going search segments a problem. either the until solves array operation the outside this leads Repeating search the row. or next found the is the than move number can in larger we card and is row, the number first move the to search in can be down the we cannot number If and search column. the column, card, preceding the last on the the number in in card number be the the cannot than to number smaller left search is the number search card, the the If on solved. is problem the same, the ned if Indeed, combined be can cases odd and even both for formulas into the that check to easy is It If h ihetaogthe among lightest the gis h ihetadhais on rvosyfudt eemn h lightest the determine to overall. found coins previously heaviest coins and heaviest and lightest the against olwn omls If formulas. following o ahpi,wihtecist n h ihe n eve fteto I they (If In two. arbitrarily.) the broken of be heavier can and tie lighter the the same, find the to coins weigh the weigh pair, each For 3(2 n h uzehsapae—ohi rn n nteWbi several Web—in the on and print in appeared—both has puzzle The h loih’ euneo undu ad om izgln aeu of up made line zigzag a forms cards up turned of sequence algorithm’s The h oa ubro egig aeb h algorithm, the by made weighings of number total The sodd, is W k ( + n ) 1) n = iietecisinto coins the Divide / seven, is 2  h loih sa plcto ftedces-yoestrategy, decrease-by-one the of application an is algorithm The − 2 n n  see,tepolmi ovd if solved; is problem the even, is 2 +  = 3 2( n n W  / seven, is  n 3 2 ( / k 2 n − n 2  + )  − = ihe on n hntehais mn the among heaviest the then and coins lighter 3 2 W / 1) = 2 2 n ( − n  + + 3 ) n n / = 2( / 2 2 2 2  =  = 2 n − ar,laigoeci sd if aside coin one leaving pairs, 3 − 3 2 3 n 2 k  .  1) = If 2 n −  n = 3( 2 = n = n . 3 sod eg h onstaside set coin the weigh odd, is 2 − n 3 2 k n −  1) + − n 2 2 / / . sodd, is 1 2 1 2 W − = = ( 3 n 3 n ) egig,find weighings, 1 2 n , / 2 sgvnb the by given is  − 3 − n 2 3 / 3 . 2 / n − 2. sodd. is  n 2 / 2 =  167 Solutions , 5 + 2 S 1or 1) is m + k + > is equal 3 n 3)(6 m k S = (6 + n m m 3 numbers. It has where (6 n = k = 2 3 n / T . = 1) n 1) 1), + + 2 + m . n (6 m ( k with a single tromino, the tiling 2 n m 2 and of the first and last steps in 6 S = 3 = S = k n . n 5 T S is not divisible by 3. Finally, if ), n m and T 2 3 +···+ S = is odd (i.e., 2 if and only if either 2 k k with trominoes to exist, it is necessary that the total + > 2 is, in fact, the minimum number of comparisons n 1 n S 2) is also divisible by 3. Similarly, one can check that if = where − is divisible by 3. The total number of squares in + n 1. , 2 n T k / m S is even or odd, n > 3 3 k is even (i.e., k  = k 1)(3 n + Essentially the same algorithm can be obtained by applying the where Impossibility of tiling of m , In addition to the obvious tiling of where 2 where 1 , 3(2 k + + th triangular number 4.68 3 n k k = 3 3 = 2 is divisible by 3 for both even and odd values of The only possible tilings of the first step in Obviously, for a tiling of The puzzle is a well-known problem in computer science, usually stated as the / n = = n divisible by 3. If n n number of squares in to the in question is possible for FIGURE T (Figure 4.68) show that these regions cannot be tiled with right trominoes. 4) If Solution Comments 96. Tiling a Staircase Region needed to solve the problem in the(see worst [Poh72]). case by any comparison-based algorithm divide-and-conquer strategy: divide thegroups, coins find the into lightest two and equaltwo heaviest lightest coins (or in and about each two equal) of heaviestoverall. them, coins and to then determine weight the the lightest and heaviest coins problem of finding the largest andbeen smallest proved elements that in a set of Algorithmic Puzzles 168 6 FIGURE FIGURE 9 S ih rmne Fgr 4.70a). (Figure trominoes right etldb attoigi no3 into it partitioning by tiled be tics regions staircase ihrgttoiosb h olwn eusv loih.Tlnsof Tilings algorithm. recursive following the by trominoes right with hw nFgr 4.69. Figure in shown 6 + + If staircase any that show will we Now If ssoni iue4.79, Figure in shown is 6( 6( n n = m m = 4.69 4.70 − − 3 3 k S k , iig of Tilings iigo (a) of Tiling )where 1) where 1) 6 , where where a (b) (a) S 6 k and k S sa d oiieitgrgetrta (i.e., 3 than greater integer positive odd an is m m 6 sa vnpstv nee rae hn2(i.e., 2 than greater integer positive even an is S and > > S 6 + 6( S S 6( ) h tics region staircase the 1), region staircase the 1), S m 6( 6( 9 m − . m m − 1) − − 1) 1) × 1) n h 6 the and n (b) and etnls aho hc ob ie ytwo by tiled be to which of each rectangles, 2 a etldrcriey n h etnl can rectangle the and recursively, tiled be can S S n 9 + × where 6( m 6( − m 1) S S . n S − n n 9 = a epriindit the into partitioned be can the into partitioned be can )rcage h iigof tiling The rectangle. 1) 3 k , k > 1 n , S = a etiled be can 6 n 6 and S m = 6( m + 6 S − 1) 9 m 3 are = = 169 Solutions , 9 k 3 1. S 3 0) × > × = k , k 3 can be tiled , = 1 mod 3 can be tiled by n and the 2 n > , T k k 3 k 3 S , S 2 , where 2 n + S S k 3 1) rectangle. The tiling of into = k n 3 − n S S m 6( where × n S 2 rectangles, each of which to be tiled by two × and the 9 can be tiled as shown above, and the rectangle can 1) 1) − − can be tiled by a single tromino, m m 2 . 6( 6( S 2 S S + k 2 3 S and S 9 S The solution utilizes several ideas in design and analysis of 8 instance of the puzzle was included in A. Spivak’s book [Spi02, Tiling of The game always stops after a finite number of iterations. = n 4.71 Finally, we will show that any staircase Indeed, the king may appear at the top of the deck no more than once because Thus, we have an algorithm to tile any staircase region The rectangle (Figure 4.71). with right trominoes as follows. We can partition the above algorithm, and the rectangle can be tiled by partitioning it into 2 if it does, the algorithm(which will has move a it smaller to value) thefrom at last there. Similarly, the 13th the top position, queen may of and appear the at nofirst the deck appearance other top there will no card and more be than subsequent able twice: move afterthe to to its top the move will 12th the be position, king able only to the move king it at from there, which cannot happen more than once. be tiled by partitioning it into 3 right trominoes (Figure 4.70b). rectangles, each of which to be tiled by two right trominoes. Solution divide-and-conquer (region partitioning), and decrease-(by 6)-and-conquer. Comments FIGURE staircase regions is shown in Figure 4.79, 97. The Game of Topswops Problem 80]. algorithms: a formula for triangular numbers, an invariant ( Algorithmic Puzzles 170 n fteetinlsi hw nFgr .2 h ubro tig spelling strings of diagonals. number diamond’s The and the 4.72. center by Figure the in formed at shown C triangles is the four triangles at the these starts of of string One such one Any in SAW. contained I is CAT spell to ways of advrino h ososgm a eetne oaystof set any to extended be can game topswops playing the the course, of Of version 76]. card p. [Gar88b, University Princeton for at 1986 iterations since working of number finite a after stops input. procedure possible every puzzle’s the that prove ntetpo h ekt tptegm oltrta fe 2 after than later no game the stop to deck the of top the on than value greater of cards Solution Comments first the after queen, 1 the times: than or more four king no the than top by the more only at position appear no final can its card which from top moved be the can it as appearance, appear may jack The FIGURE pligCTISWi h triangle. the in SAW I CAT spelling efral rvdb nuto,tecr fvalue of card the induction, by proved formally be h o ftedc omr hn1 than more no deck the of top the salse ihahl facmue rga Ku1 .721]. was p. which [Knu11, program moves, computer 80 a requires of game help longest a the with fact, established In cards. other the all of there 8 aidoeCounting Palindrome 98. to 1 from values (1 W ssgetdb h itt hspzl,w a tr ycutn h number the counting by start can we puzzle, this to hint the by suggested As h aewsivne n ae yJh .Cna,aBiihmathematician British a Conway, H. John by named and invented was game The + 2 W W A +···+ 4.72 W A W S A h nwri 63,504. is answer The imn fltesadtenme fwy orahec etrfo while C from letter each reach to ways of number the and letters of Diamond W S S W A A I hsi neapeo nagrtmcpzl hs betv sto is objective whose puzzle algorithmic an of example an is This 2 n A I W I W T S A S 12 rte nthem. on written − W A S I T T A I S A i W ) = W A A S I C T I S A W A T 2 i 13 a pera h o.I atclr h c ilappear will ace the particular, In top. the at appear may T T W − W A S I A I S A i − I I W A S W T S A sa pe on o h ubro ie the times of number the for bound upper an is 1 + W W A S A I S (1 + W W A A S 2 W W A +···+ + 2 W = ie.I eea,wihcan which general, In times. 3 i , 2 C T I A S A W 2 12 1 1 1 1 ≤ 1 1 − 1 W A A I S T i ) i 6 4 2 5 3 = 1 ≤ W I S A T 12 2 15 1 13 3 6 10 13 − n I S A W − , ≥ 1 appearances 1 4 i a perat appear can 10 20 A S ie,where times, ad with cards 1 W 1 5 15 W A 6 1 W 1 171 Solutions . 2 s 4) − 6 2 · . 4 / 1 such passes the 2 1) − k − n 0) in a diamond-shaped . ( [Loy59, Problem 109]; it is even, the first card with n > first to the numbers in odd n = n 2 4 card exchanges, which is the [Dud02, Problem 30] with the / 1) 2 1) − k − ( 1 letters ( n = + 2 n / or 1) 0), the problem can be solved by applying a 4. (We need to subtract 4 to compensate the 2 exchanges for the cards in the odd positions . / − 6 > − k 2 exchanges on strictly decreasing arrays of size k / 6 k 1) s 2 , 2)( The Canterbury Puzzles · . 1) − 1 2 − k − − ; it has no solution for any even 4) k s n ( k Mathematical Puzzles of Sam Loyd 2 exchanges for the cards in the even positions, yielding the − 2 / + n 2 1) = 2 · / n − k In addition to dynamic programming, the solution exploits symme- k 1) The puzzle can be solved with ( − 2)( k ( − is odd ( 504. k n , If Any sequence of allowed exchanges can only swap cards that are either both in This number of exchanges cannot be decreased by the following reason. We are Bubble sort makes ( The total number of strings spelling CAT I SAW for the entire diamond is then The puzzle is from 63 the largest number cannot be moved to the last position that is even. even positions or both in odd positions. Therefore, if total of arrangement: (4 Therefore, it will make ( minimum, for any odd obtained by the formula 4 only allowed to exchange adjacent elements in the two sorted-in-reverse sequences such as positions and then to the numbersby in exchanging even out-of-order pairs positions. of Both adjacent these elements.is algorithms For applied work example, to if the bubble odd-position sort numbers,third, it then will the exchange third the with first the numberthe fifth, with last and the position. so Then, on, on until theposition the will second largest “bubble pass, up” number the to ends its second up final largest position in number and so in on. an After odd overcount of the strings along the diamond’s diagonals.)number This of ways implies to that spell the WAS total IT A CAT I SAW is given by the formula (4 odd-position numbers will be sorted. Solution Comments = CAT I SAW in the triangleprogramming (see can the be tutorial on found algorithm by design strategies). thebe These standard computed numbers can application by of diagonals dynamic paralleladjacent to numbers the to the triangle’s left hypotenuse and below by thePascal’s adding letter triangle. up in question. the The These numbers sum form diamond’s of border—is these equal to numbers 2 on the triangle’s hypotenuse—the 99. Reversal of Sort and ( try twice by counting occurrencesthe of given the shape. half of the palindrome in the quarter of also appeared in Dudeney’s letter R instead of the letter C. Dudeneyof also ways gave a to general read formula such for the a number palindrome of 2 Algorithmic Puzzles 172 a eotie yapyn h tnadfruafrtesmo h em nan in terms the of sum the for formula standard progression: arithmetical the applying by obtained be can h aeof case the rwti h cao ihtecne ttesatn qaeadhrzna and horizontal boundary and the square on starting the lie 2 at that of center made square the sides starting vertical with the octagon of the color within the or to opposite color the R Solution Comments positions. even-numbered and odd-numbered of number the total the in decreases cards operation This the by formed Comments reachable of number total the for for squares formula following the implies immediately This ih2 with h trigoe odrv oml for formula a derive To one. starting the foeain euigtenme fivrin yoea time. a at one by inversions sequence of any number for the necessary reducing exchanges operations of of minimum the is number same the Hence, ogun rpzisaoeadblwtercage h etnl smd up made is rectangle The rectangle. the of below and above trapezoids congruent hnall than atto h cao notecnrl(2 central the into octagon the partition nFgr .3 scnb enfo htfiue h ubro itntsquares distinct of number the figure, that in from knight seen the by be reachable can As 4.73. Figure in htfrayodd any for that n oo,frtettlo ( of total the for on, so and n 0.AKih’ Reach Knight’s A 100. Gk6 p 48–49]. pp. [Gik76, 2 re—ntersqec yoe h oa ubro nesosi strictly a in inversions of number total The of one. sequence decreasing by sequence their order—in , (2) ≥ h qae ecal ytekih in knight the by reachable squares The h uzei netnino rbe 5 n[y7] hc nyconsidered only which [Dyn71], in 155 Problem of extension an is puzzle The respectively. n 2 + 3 [ = R , n ( osec ih2 with each rows 1 h nydfeec steclro h qae,wihi h aea htof that as same the is which squares, the of color the is difference only the ( n s 33 n ecal qae.Tenme frahbesursi h trapezoids the in squares reachable of number The squares. reachable + − ) n , n h nwri 7 is answer The = 1) lmnsfloigi,tescn n slre that larger is one second the it, following elements 1 and = ≥ h rbe a nlddi .Gik’s E. in included was problem The inversion. and parity of those is exploits puzzle the themes main The (2 + 100. 3: R n n ( (3) + n ≥ + 1)( 3 = 2) s n , lmnsi qa o( to equal is elements n l h qae ecal in reachable squares the all + 76 +···+ + n n s n . 2 qae seFgr .3 for 4.73c Figure (see squares 1 − + 1) ti o ifiutt rv ymteaia induction mathematical by prove to difficult not is It + moves, 1) ecal qae,itroe with interposed squares, reachable 1 + 4 n + 2 2 + n n ( 2 R ]= s for 1 + ( − n R ,for ), (3 n 2) 2 ( n n + n n n where ) +···+ ≥ + + s 1) = − n 3 inversions 1) 1 2 , × = 1) 1 + n ti n 3for 33 and 8 is it and n , ahmtc nteChessboard the on Mathematics s (4 = 1 2 2 / n n , n :tefis lmn slarger is element first the 2: , 1 n ≥ 7 n 2 oe r h qae of squares the are moves n oe r shown are moves 3 and = n + , toeeet u of out elements —two = 2 3 n 3 and ( , )rcageadtwo and rectangle 1) + n s (3 ecn o example, for can, we − = 4 n n 1) , + ) o n even any For 3). + s are s − 1) / 1 inversions. 2 n . n elements, 2 R . n oseach rows (1) = and 1 = 8 , 173 Solutions + 11 + [Fom96, p. 68]. (b)(b) Mathematical Circles S (c)(c) 30 room repaintings for the half of the rooms in the palace. The S (a)(a) = The solution takes advantage of the palace’s symmetry, which can be 1) Squares reachable by the knight from square S in (a) one move, (b) two The algorithm presented in Figure 4.74 requires the total of 13 + 3 4.73 + 1 + The puzzle is based on Problem 32 in moves, and (c) three moves. Comments Solution (1 101. Room Painting FIGURE other half—symmetric to the first onetaken with care respect of to in the the main same diagonal—canthe be manner. rooms Thus, 60 times. the entire job can be done by repainting considered a divide-and-conquer application. Algorithmic Puzzles 174 FIGURE Solution Coconuts the and Monkey The 102. opittesursblwtemi diagonal. main the below squares the paint to ooustknb h rt eod hr,fut,adfit alr epciey and respectively, sailor, fifth and fourth, third, let second, first, the by taken coconuts olwn ytmo qain sobtained: is equations of system following 1 Let f etenme fccnt aho hmrcie ntemrig hnthe Then morning. the in received them of each coconuts of number the be n 4.74 eteiiilnme fccnt,let coconuts, of number initial the be h nwri 15 is answer The ouint the to Solution 3 omPainting Room 4 , 621 5 . 4 4 4 4 4 d n a b c e 6 ======5 5 5 5 5 5 uze h ubr niaeapt ordering path a indicate numbers the puzzle: f e d c b a + + + 2 + + + 1 1 1 1 1 1 . a , b , c , d , and e etenme of number the be 175 Solutions , f and are the 1 must , 5 e + 4 , d f = , c , 1 , b 1) + , 4 and a f + 1) + f n + and e 6 1)( 5 1)( + = . e . + 4 1) d 1) 1)( 1) 1) 1) 1) 1) + + + 1)( + + n + + f + + f ( d d e a b c + 6 5 5( 5( 5( 5( 5( 5( c 1)( ======1)( + 4 c 4) 1) 1) 1) 1) 1) + + b + + + + + + 1)( n e c b n a d 1)( + ( 4( 4( 5 4( 4( 4( b 4 + a respectively. Hence, 1)( column and then in [Gar87, Chapter 9]. His discussion , 5 4)( + (Obviously, all the other unknowns, i.e., . a + ( 6 n 621 5 and 4 ( , 5 6 4 = 15 The solution given above was suggested by R. Gibson, a high school The answer is “no.” = 4 − Scientific American 6 Color the board’s positions as squares of a chessboard (Figure 4.75). As mentioned in the first tutorial, some puzzles can be solved by reducing them Different versions of this puzzle has been known for a very long time. David is 5 be divisible by 5 smallest natural numbers that satisfy the equation.n Therefore, the smallest value of Solution will also be positive integers as well.) Comments The last equation implies that if it has an integer solution, or After multiplying the left- and right-hand sides of the equations, we obtain The easiest way to solve thefollowing: system is to add 4 to each of the equations to get the 103. Jumping to the Other Side student in South Africa, in 1958. to mathematical problems. The aboveapproach. solution provides a good example of this Singmaster’s annotated bibliography [Sin10,dozen Section pages 7.E] to references devotes dealing more within it. than his Martin a Gardner discussed this problem contained some entertainingmethods anecdotes for about solving the it,or including puzzle’s colored an coconuts history to ingenious simplify the and method computations. of a adding few four fictitious Algorithmic Puzzles 176 loe oepeevsteclro one’ oiin h uzecno be cannot puzzle any the Since position, squares. counter’s dark a the of color solved. on the positions preserves destination move 6 allowed only are there whereas 0.Pl Splitting Pile 104. of Wegman Mark to Center. problem Research Watson the J. Thomas attributed IBM’s from Gardner problem 335–336]; a of pp. reader, [Gar97b, a by Gardner Martin to suggested Solution Comments FIGURE hc a eesl ovdb akadsubstitutions: backward by solved easily be can which nec pi.Telte ed oterecurrence the counter to one leads aside latter setting The by split. piles each the obtain on splitting or of way puzzle, simplest the the of considering instances by small it of inspection in emerging tutorial) second numbers triangular nedeulto equal indeed onesinto counters done. splits h u osntdpn nawytesltigi oe st oml for formula a to As done. is splitting the way products, a the of on sum depend this not does sum the eei tagtowr ro ysrn ahmtclidcinthat induction mathematical strong by proof straightforward a is Here squares, dark the on are 9 counters, the by occupied positions 15 the of Out optn h u ftepout o ifrn ast pi ieof pile a split to ways different for products the of sum the Computing P ( 4.75 n ) = = .Tesmo h rdcsi qa o( to equal is products the of sum The a. ooigtebado the of board the Coloring P ( ( h uzei ae na nain da ti io modification, minor a is It idea. invariant an on based is puzzle The ( n n n n − − ) ie o h rtfwvle of values few first the for piles n ( = 1) 1) n tesm ftefis osctv oiieitgr—e the integers—see positive consecutive first the of sums (the − 1 + + · 1) ( ( P n n / ( P n − n osntdpn nawytesltiginto splitting the way a on depend not does and 2 − ( n − 1) 2) ) , 1) + n a ihrnt h atr fteso-called the of pattern the note either can one +···+ = P upn oteOhrSide Other the to Jumping ( ( n n − − 1 )for 1) 1) + + P (1) ( n n n ed n ohpteiethat hypothesize to one leads > − n = − 1 2) , ( n 1) + P − n (1) puzzle. P / 1) h atRecreations Last The repcieo the of irrespective 2 ( n = n − / 2 0 2) . , = ... P ( n )is n n 177 Solutions + + (1) ) n k ( 2 and ( n ] / then by 1 M . 0 checks counters = , [ 1) 0 1 n − . n ) − = 1 − n 2 = n 2 ( < leads one to / k ≤ / − ( k k ... k M max n 1) (1) k 2 1) ≤ (1) . 1) + / 1 = ≤ 0 We will show that M + . M − n . 1) + − 1 k n = k 2) n k − + − − , 1 satisfies the equation − − 2 < 1 and hence Indeed, if the initial pile 1 n = − 2 n k . (1) j ( n . n − ] / ) n ( n = n )( > 2 n M + )( 2 ≤ k 1) ( )( k k M / n = = − k , nk M − + j 1) 1 − + 2 2 − n n / for n (1) ( ( + ) ] n > ( 1) − n ) n j ] ( M counters where 1 n 2 ( k ) + j + − n k + k + 2 1 + 2 2 n − 2 for every 1 = ( + / − 2 − n n − 1) . ] ) ( ( k n ) n j 1) + 2 ( k ( − 1) 1) for / M n + − − k M M − − 2 1) 2 ( − ) for the first few values of and + k = j nk k k n ( n + n ) k ( ( + ( k ( +···+ k ) 0. Assume now that the assertion is correct for any − + 1) + n k ( M k M M 2 ( 2 + ) ( 1) = − k M k k k 1 satisfies the equation = + ) [ [ [ M 2 + n k 1 1 1 [ ) − n − ( − 1 n k − − − − n (1) respectively. Hence, we have the following for the sum in n n n − 2 ( n − ( M − 2 P , n / ( ≤ ≤ ≤ = n M 2 k k k kn k , 2 ≤ max max max ( [ + + ) 1) / k 1 2 n 2 ≤ ≤ ≤ max k 1 n 1 1 1 n n ≤ ( − 1) + 1 j = = = = = + + + n ≤ = = M n − ) k + ( n n n max ) n n ≤ k n n ( 1 Using the inductive assumption, we obtain: we will prove that it is also correct for ( = = = P = . − = ; ] + ) we have the following recurrence: M ) n ) n n ) j , n 1 indeed satisfies recurrence (1) as follows. The basis k ( n ) ( )( ( n < = k − M ( − M j counters is split into piles of M ) 2 j n M − Computing the values of It is not difficult to verify by strong mathematical induction that b. The maximal sum of theDenoting sums the is maximal equal sum to that can be obtained for the initial pile of n / ( ( ≤ n hypothesize that the sum of sums is maximized when out immediately. Assume now that 1 M ( the inductive assumption the sums for these two piles are equal to then by question: of M 1) The solution tosubstitutions: the last recurrence can be easily obtained by backward piles is done. If Algorithmic Puzzles 178 trswt h yblM hc steol curneo hssmo ntestring. the 2.) in Rule symbol clarify this to of observation occurrence this only need the (We is which M, symbol the with starts puzzle. uhn h utn ubrdfo to 1 from numbered buttons the pushing a eotie yapyn ue iia otoeo hspzl sipratto important is rules. languages puzzle such computer using this high-level defined of are particular, strings in those reasons; which to several of similar for science rules question computer applying The by techniques. obtained analysis be algorithm can on tutorial the in Puzzle MU The 105. flavor. programming dynamic a has (b) part in problem The Applications Its and n y3 hssrn antb eie rmM o which for MI from derived be cannot string this 3, by band o h trigsrn MI, string starting the For obtained. Solution Comments proof. the completes which function quadratic the Since Solution Comments f,apyteagrtmt h first the to algorithm the apply off, h nevlsendpoints interval’s the y3bfr h hne ic o h agtsrn MU, divisible string not target was the it for if Since 3 change. by the divisible before is 3 that by number a in result can operations these of change 3 and 2 Rules n iiil y3. by divisible 0.Trigo ih Bulb Light a on Turning 106. Bach Escher, utn1 If 1. button n / − + 2 osdrnow Consider derived be can that string any that see to easy is it given, rules the inspecting By h uzewsitoue ntefis hpe fDulsHofstadter’s Douglas of chapter first the in introduced was puzzle The , utn.I hsfist untelgto,ps button push on, light the turn to fails this If buttons. 1 1 h idepito h nevl1 interval the of point middle the ≤ max k ≤ n − ti mosbet hneM noM yuigtefu ue fthe of rules four the using by MU into MI change to impossible is It h uzecnb ovdb h olwn eusv loih for algorithm recursive following the by solved be can puzzle The 1 n Hf9 sa xml fafra system. formal a of example an as [Hof79] [ k h ouint h uzei ae nteivratmto discussed method invariant the on based is puzzle the to solution The Rosen’s K. (a)—see part in problem The > 2 − n h ih sof pl h loih eusvl otefirst the to recursively algorithm the apply off, is light the and 1 n nk , Rs7 .22 rbe 4—sbsdo nivratidea. invariant an on based 14]—is Problem 292, p. [Ros07, h ubro ’ curne ntesrnsta a be can that strings the in occurrences I’s of number the n + yduln taddcesn tb ,rsetvl.Neither respectively. 3, by it decreasing and it doubling by k ( = n 2 and 1 + k 2 n − ) / n k nk 2 − = − ≤ + utn again. buttons 1 n n 2 = − k ( ]= n = ≤ n 2 .Therefore, 1. 1 . , + n n n If ( hc sntdvsbeb .Only 3. by divisible not is which +[ − n n n ) + 1 / = 1 , 2 2 1) tatisismxmlvleat value maximal its attains it − n h ih sof push off, is light the and 1 n − / = 2 tan t iiu at minimum its attains 2 n n − · n n ec sdivisible is hence and 0 = 1 n,i h ih sstill is light the if and, iceeMathematics Discrete 1 + , n ec snot is hence and 1 ( n 2 + n ) / 2 Gödel, − 2 ] 179 Solutions th bit from i right to left and n , 1 zeros and generate n = (1) , which can be constructed M , 4: 1 . After briefly reviewing a rather generate recursively the list of bit = > , n 1 n > n 1 for (See the second tutorial where the same + . 1 . For example, for four switches, it will guide us Tower of Hanoi 1) i puzzle is solved.) − − 121312141213121. binary reflected Gray code n one of them represents an initial state, the remaining n 2 ( ; n M and the = 2 ) n = ( ) 1 switch combinations will have to be checked. To accomplish M n 1 and make a copy of this list; then add 0 in front of each bit Tower of Hanoi ( 1, return the list 0, 1. If 1 bit strings by changing just a single bit at a time. The most well- − − M n − = -bit string in which 0 and 1 represent, say, the initial and opposite n The first solution is based on the decrease-by-one strategy. The n n n Chinese Rings 0000 00011100 0011 1101 0010 1111 0110 1110 0111 1010 0101 1011 0100 1001 1000 1 bit strings contain the one that will turn on the light bulb. In the worst − To return to the puzzle, we can number the switches from 1 to The recurrence for the number of button pushes in the worst case is Alternatively, since a switch can be in one of the two states, it can be thought of There are several algorithms that start with a bit string of The puzzle was proposed and solved by J. Rosenbaum in 1938 [Ros38] by n 2 all the other 2 strings of size use the sequence of the Gray’s code bitpush: strings if for the guidance next about bit which string buttons differs to from its immediate predecessor in the string in the first list andappend add the 1 second in list front in of reversed order each togenerates bit the the string first following in list. bit the For string example, sequence second the for list; algorithm finally, known of them is the so-called as follows. If case, all these 2 recurrence for the as a bit in an states of the switch,configurations) respectively. is equal The to 2 total number of such bit strings (switch Comments whose solution is this with the minimum number of buttonswitch combination. pushes, every push must produce a new convoluted history of Gray codes, D. Knuth concluded that it is the Frenchman second solution takes advantagerepresent switches of and two their strategies:generate the Gray buttons representation code). by change bit (to strings) and decrease-by-onethe method (to described above—years before theGray U.S. code patents invention. were M. Gardner granted mentioned forcodes this the [Gar86, puzzle p. in 21]; his article thepuzzles: about article the Gray also included applications to two better-known the right, we push button number to push the buttons in the following sequence: Algorithmic Puzzles 180 scudhv apndi h or eels hn1 el og If long. cells 11 than less were board the if happened have could as of that to adjacent position a in be never will he hare. and the fox, the by move a before even ae ec,teprt fterpstoscag oteopst nec move, each Therefore, position unchanged. on initial positions opposite the their the if between difference to the change of positions parity the their leaving of parity the Hence, hare. opsto .Smlry if Similarly, 1. position to Solution Gros’ of view in code this of inventor the on true book a 1872 considered be should who Gros Lois o2 ae h iuto nlgu otefxsatn n1adtehr starting hare the and 1 in starting fox the to 25. analogous at situation the makes 26 to lomkn h e iuto iia ota of that to similar situation new the making also h aejmsbc o7 n oo.Tu,tefxwl ee ac h aein hare the catch never 5, will to fox returns the fox Thus, for the on. If jumps so 4. hare and If and the 7, case. 1 Then this to between 6. back alternating to jumps starts advancing hare and by 7 the 4 him between to catch forth fox to and the tries a back over without lead fox jump hare have the simply the would until can leaving which 10 hare and 1, and the 4 to that, to if (not After move 7; 7 fox’s to move). to the returns possible back hare after the defeat jumps 1, immediate hare to the the returns to 3, then to fox moves the fox If 4. the position to jump can hare epciey h o n aecnb eoethe before be can hare and fox the respectively, H 0.TeFxadteHare the and Fox The 107. aecnjm otergto i rttomvst oiin9 aigtenew the making 9, position to moves of two that first either his to on similar right situation the to jump can hare F oiin otergto h o.Hne ftefxde o ac h aebefore hare the catch move. not next does his fox on this the do if will he Hence, odd 26, fox. position some the reaching hare of the and right board position the the leftmost to the with positions in game fox the the position, restarting one to by next can equivalent shortened the on hare becomes on caught the caught situation be more, be can the or hare to or the 5 either fox is move cases, difference the these all the of In if direction. left right; either in the the jump to to jumping jumping right, or the of move to next choice moves simply the fox a fox the with 3, the is hare 1, difference the the to If leaving equal move. is next the difference on the hare the If catches difference odd. the with being fox, the positions of right their the between to starts hare the Indeed right. the to moving w oe rt htof that to or moves two (1) (1) o iltehr oebcueo nighmefwtotalgtmt move, legitimate a without himself finding of because lose hare the will Nor osdrteprt ee rod ftecells the of odd) or (even parity the Consider If s s = = see,tefxcnfretehr noapsto ett tb ipyalways simply by it to next position a into hare the force can fox the even, is = lostehr oaodtefx If fox. the avoid to hare the allows 7 and 1 s nec oe hi oiin hneb o h o n y3frthe for 3 by and fox the for 1 by change positions their move, each On . h o a ac h aeif hare the catch can fox The s sa d nee ewe n 7 nlsv,tesm taeyused strategy same the inclusive, 27, and 9 between integer odd an is H (1) hns Rings Chinese = s ftehr sod h aiyo h ifrnewl remain will difference the of parity the odd, is hare the of .Atrtefxmvst oiin2o i rtmv,the move, first his on 2 position to moves fox the After 7. s s = = ftefxfis oe opsto n hnreturns then and 2 position to moves first fox the if 9 5 , Ku1 p 284–285]. pp. [Knu11, h aecnjm opsto nhsfis move, first his on 8 position to jump can hare the s = ftefxmvst oiin3o i first his on 3 position to moves fox the if 7 s see,adh antif cannot he and even, is s = n hmv.For move. th s 29 = , F 7 h rtjm ytehare the by jump first the ( . n e now Let and ) n H s = sodd. is s ( n 1 = nwhich, in ) , s F ,ta is, that 7, = (1) 3 , = the 1, 181 Solutions , n 6 One ≤ 5 and ’s and j n ≤ = 5 n the longest 2. , / 6 for odd 2) 4  = 2 + / n n n X  ) tiles where 0 1)( j , 3 4; for ) tile. Therefore, the total + n is even. n ,... , , ( → 1 1(0 n n It is easy to see that the routes . , later republished in [Gar71, 2 . 1 = − + 2 n n n 1 − , → 2  [Ste64]. ’s—can be made longer by replacing 5 , One Hundred Problems in Elementary n 2 n n 2is 1  , → ≥ + +···+ 1 n n n 5 and finally one ( 3. The solutions to the problem are not unique → 1) + 2 1 for even Scientific American − → 1) n + 5 ( ,... , 5is3 + 2 n 4 / n = n → domino set consists of ≤ , n n 2 j 2 X / ≤ n → 6 3 Dominoes n → 6. The puzzle provides an interesting example of a greedy algorithm The solution exploits two ideas in algorithm design and analysis: ,... , by Hugo Steinhaus [Ste64, Problem 64]. It was also included in one 1 1 The longest routes obtained by adjustments to the greedy solutions for = a. A double- Assuming that the distance between two adjacent posts is equal to 1, − n is odd and at one of the two middle posts if → 2 n 4, but any longest route must either start or end at one of the three middle n 4.76 , ) tiles where 1 2 j > 6). The proof that the greedy paths adjusted in this fashion are indeed the 5 and , , n n The longest path for Let us number the posts sequentially from 1 to As mentioned above, the puzzle is from The puzzle is a modification of a similar game from [Dyn71, p. 74, Problem 54]. = = (1 , 1 number of tiles is equal to ( n for longest is not difficult but rather tedious; it can be found in Hugo Steinhaus’s Hundred Problems in Elementary Mathematics 1 path is 4 n the last segments of these routesof by the the longer greedy segments routes connecting to the post last 1 posts (see Figure 4.76 illustrating the cases of n obtained by the greedy strategy—that is, 1 Solution Comments FIGURE Solution Comments posts if yielding a solution that is not optimal but which can be easily adjusted toMathematics be one. of Martin Gardner’s articles in 108. The Longest Route parity and decrease-and-conquer. the length of the longest route for any 109. Double- pp. 235, 237–238]. Algorithmic Puzzles 182 ti h aefrtegahi usini n nyif the to only solution and the if in outlined question (#28). is in puzzle circuit graph Euler an the constructing for degrees. for even case have vertices the its all is if only It and analysis—a if circuit algorithm Euler on an has tutorial graph book’s all connected this of example, by in ring for represented circuit a theorem—see, be Euler specify known an can would Obviously, they graph themselves). a or to such spots, vertices any of connecting between number (edges inserted same loops then the and with constructed dominoes is two dominoes other the all including i olw.If follows. nElrcruti opeegahwith graph complete a in circuit Euler an pt n h te afcnann ifrn ubro pt,adteei also is there and spots, with of containing halves number both different with a double containing one half other the and spots h sdi ofidtenme fdfeetarneet fadouble- a of arrangements different of Tarry, number Gaston the mathematician find French to the set. domino 251] it to p. used [Bal87, idea Ball who reduction Rouse reduction. the problem solution, attributed alternative the in and, eann oios( dominoes remaining If Comments olwdb (2 by followed ntedouble-(2 the in pt nterajcn avs h ubro ie ihhle containing halves with of tiles number of same number the the have halves, must adjacent ring their a in on tiles spots adjacent of pair every Since number. eunigquartets sequencing qa to equal (0 nti rp ersnsapsil ubro pt noeo h w avsof halves two the of one on spots of number possible an a represents graph this in sepr b) osc igi osbewhen possible is ring such no (b)), part (see utb vnfreey0 every for even be must (2 and n , lentvl,oecnrdc h rbe oteqeto bu xsec of existence about question the to problem the reduce can one Alternatively, .Freeyvleof value every For b. When .Arn nqeto a ecntutdi n nyif only and if constructed be can question in ring A c. n )in 1) t = dmn,ada debtenvertices between edge an and -domino, , k 2 j 2 pt seulto equal is spots s pt nishle.Tedulscnb ihreiiae ni ring a until eliminated either be can doubles The halves. its on spots s

− R where , n n (2 k n see n oiie eurdrn a ecntutdrcrieyas recursively constructed be can ring required a positive, and even is 1)(2 = = s 0 h uzeepot eea hms aiy decrease-and-conquer, parity, themes: several exploits puzzle The − s ,teei utoering: one just is there 2, k , s ( ) ial,slc hscanbtenteajcn ar(0 pair adjacent the between chain this splice Finally, 0). s s )t e igmd po l h double-2 the all of up made ring a get to 2) n − > − R + 1 2:(0 (2): ,cntutrcrieyaring a recursively construct 1, )dmn ust hncntutacancmrsn the comprising chain a construct Then subset. domino 2) , 2) i 2 , n t k j = ≤ ,where ), + ,0 + , k n 1)(2 .Hne h oa ubro pt naltetlsis tiles the all on spots of number total the Hence, 2. ≤ 0)(0 ( ≤ n k + n t ≤ , ic hsnme seulto equal is number this Since . j + 1)( 1)(1 = n 1 hr are there , n , 2 2 , k + s s 1)(1 − pt.S,tettlnme ftehalves the of number total the So, spots. n )(2 2) dmne,advc es.B well- a By versa. vice and -dominoes, n n n 2 and 1 / s i , sodd. is + , 2. and 2)(2 2 n t etcs Vertex vertices. 1 + ie ihoehl containing half one with tiles R j , s , (2 )for 2) ersnstedmn with domino the represents 2)(2 0 s ≤ − n , see.A algorithm An even. is 0) s i )o l h dominoes the all of 2) t dominoes. ≤ n = . sapstv even positive a is j 0 , n , o xml,by example, for + 1 iueTracing Figure i .., ,... ,0 o every for 2 ≤ , k s )and 0) i − spots ≤ 1 n k k n , 183 Solutions  1 2 + / ) 2 − k / 2 is odd, ) / k − k ) k n − − ( . Finally, the 2 coins must −  n n  ( n 2 1, respectively.  − ( If / (  ) . k + k k (which is equal to − k −  n − − n 2 coins.) Let us find the n / n ( ) k k (We assume that the rows + − . k n n coins must be moved into this ( k ≤ k − n − 1 leftmost coins and ≤ 2 / ) th row contains − k k 2 is even or odd) leftmost coins from row / − ) k k n ( − . − coins in the last row. Then  rightmost coins in the last row are moved to the  n n 3 k  ( / 2  n / )= T ) k , respectively; this will leave exactly  k k 1 of the given triangle; it is convenient to take these coins − 1 rows of the given triangle are moved in the reverse order, − n n + − ( ( k  k − are moved to the right end of row 2 coins is n  / 2 The puzzle is based on a rather rare version of the invariant idea. / 1) )= )  The minimum number of coin moves needed to invert a triangle with The answer is “no.” k + 2 / − n ) ( n k n ( − = To invert a coin triangle in the minimum number of moves, we obviously need After two chameleons of different colors meet, the number of the chameleons Figure 4.77 illustrates the solution for the case of even n − n th horizontal row of the triangle given, 1 ( are counted top to bottom, so that the be moved into row coins from the first we can also move one moreend coin to from get the a right end symmetric of solutionare each to illustrated row in the Figure than one 4.78. from described its above. left These two solutions This operation is repeated until rightmost coins are moved to the right and left ends of row row. It is convenient to take these coins from the last row as follows: 0 or 1 depending on whether minimum number of coin moves needed tothe invert base the of triangle the by inverted making triangle. this To row do this,  to use one of its horizontalk rows as the base of the inverted triangle. Consider the of their colors willcolor decrease will by increase 1 and bydifferently the colored 2. chameleons number Hence, will of not oneby chameleons change 3. difference of and Therefore, the the the between division-by-3 two other thechange. remainders others This of numbers will immediately all increase implies the of that three the forall differences the the will chameleons data not become given the it same willand color. be 5, Indeed, impossible the and for initial therefore differences their arechameleons division-by-3 4, could remainders 1, become are the 1, same 1,be color, 0, and with one 2. the of division-by-3 But remainder the if equal differences to all 0 would the as have well. to right and left ends of row n leftmost coins and Solution Comments 110. The Chameleons Solution that is, from the longest to thebase shortest, row. to form successive rows below the original from the penultimate row: its 111. Inverting a Coin Triangle Different versions of(e.g., the [Hes09, Problem puzzle 24] and have [Fom96, p. 130, been Problem 21]). included in several puzzle books T Algorithmic Puzzles 184 FIGURE FIGURE M lengthened shortened. be be must must that that row row a M in a coins in of number coins the decreases of simultaneously number and the increases move coin each the make to needed minimum ttoaycis respectively). coins, stationary netdtriangle. inverted netdtinl ( triangle inverted ( ( h oa ubro oe aeb h algorithm, the by made moves of number total The k k ) follows: as computed be can ) = = = 4.77 4.78  (  ( n n

− j − netn ragewith triangle a Inverting netn ragewith triangle a Inverting = n k 0 ) − k 2 / ) 2  k +  (  n , − − + n n ml ice niaecneso h de,mvd and moved, added, the of centers indicate circles small and , − 2 k 1  − k  2 n j + ) − k 2 + 1 hrwtebs fteivre rage because triangle, inverted the of base the row th  k

k j =  − − T T 1 1 10 + 8  j on ymkn row making by coins = on ymkn row making by coins n ( k − 2  − ( 2 n k

− j 1) =  k 0 ) k / 2 .  ( n n − 2 − k k M  ) − ( k + k k ) = =  1 , (  n

h aeo the of base the 3 sovosythe obviously is − h aeo the of base the 4 j = + k 0 ) / 2 (  k 2 − j 2 + 1)

k j k = − 1 1 j 185 Solutions , k i = 3 . . − k 2 n = n 2 1) n + + 2 n n ( + + k k 4 4) 4) 4 . to find a compact + k 1), the problem has + n n + (2 3 rounded up and down, i ) is attained when (2 / 3 k − . (  2 − 2) k = 3 2 M / 3 + k n  3 n 2) n = 3 T k + =  n 1) k ( 2 = − Scientific American 1) k  2 ( = − 1) k + − ( k is even (see Figure 4.77 for an example). 1 ) can be further simplified to + 6 i k + n + 2 ( ( and k 2 k n M =  −  2 3 3 − n 3 is an integer (i.e., if / / n / 2—into this formula to verify that it does yield the same  2) 2) 1 2 is the total number of coins in the triangle. One can  2) + / 1 i + + + + 3 1) n 1 1 + ( n = k − + + i k 2 n n 2 = − ( 3 is not an integer, the problem has two qualitatively different (3 − As pointed out in the book’s first tutorial, reducing a puzzle to a n n / + n and So, if ( k −  2) ,  = . obtained by the above algorithm with ( 1 3 7 1) = n + = is even, the above formula can be further simplified to is odd, the formula for / + ) T ) k k n + i k 2) k i ( 3 ( − − + The minimum number of coins moved can also be expressed by the formula In either case, the minimum of the quadratic If ( This puzzle has been around for a long time. For example, Maxey Brooke (3 M M n n = We consider solutions qualitatively different if they have distinct rows of the given triangle as their n easily check this assertion by substituting each of the possible three cases— that is, with mentioned in references [Gar89, p. 23], [Tri69], and [Epe70]: answers as the ones obtained above for the optimal choices of a unique solution (in terms of the coins that remain stationary) because then 7 Comments n where = ( If If bases. One of these solutions—the one withtriangle an odd to number of the coins base moved from ofan the an example). base of inverted the triangle—will given have a symmetric counterpart (see Figure 4.78 for solutions formula for the minimum number ofinstance of coins the that problem. need As a to solution, be he([Gar89, used moved p. the 23]): in following “In “geometric” this working approach on general the general problem, for equilateral formations of mathematical problem is one of the varieties of thein transform-and-conquer algorithm strategy design. included the 10-coin instancewinner,” in that his is, book a bet—which [Bro63],won’t should referring be win to more able it often toreaders than as find lose—that of a someone a “coffee his three-move March solution” 1966 (p. column 15). in Martin Gardner asked Algorithmic Puzzles 186 a lasb adi nqewyaogtee“corridors.” these tiling along a way of unique Dominoes a 4.79b). in and laid be 4.79a always Figures can (see removed the other if each “corridor” to one just next and are other squares each to next removed not are the These latter at the them. endpoints if the squares introduced with “corridors” had two into who board the Gomory, partition barriers Ralph mathematician U.S. the after Solution Revisited Tiling Domino 112. [Dem02]. see constraint, a at such under touches coin another it one to which where transformed under be location conditions can of new arrangement exploration its general a to outside For it coins. an other sliding taking two and least always given by triangle triangle triangle cut-off the a inverted from in the coin coins in the all locations slide designated can their coins we coins to row, other moving horizontal two than a touch Rather by to 13]. row that p. horizontal so [Gar89, a position” position new new its a determine to rigidly to slid that be easy must it “on coin that makes a requirement move triangles additional the each cut-off satisfy to the above Using outlined algorithm optimality. the provided modify solution’s authors the the of of neither but proof given, triangle a a off cut be to need that triangles remainder.” the ignoring and 3 is by pattern coins the of In invert number to coins. the moved of dividing be number by must maximum obtained that a coins of encloses number it inverting smallest that the billiard), so case of figure every game the a over for it balls placing 15 bounding and the a it group drawing to of used that frame is the problem (like the triangle that realized have may readers size, any FIGURE ruet h ubro qae ob oee sodweesaydomino any whereas odd is covered squares. of be number even an to only cover squares can covering of number the argument: ares a w isn qae r o daet b w isn qae r etto next are squares missing Two (b) adjacent. not other. are each squares missing Two (a) barriers. poieclrcnawy etldwt oios For dominoes. with tiled be always can color opposite For fcus,tepolmhsn ouinfrodd for solution no has problem the course, Of ohTig[r6]adEesn[p7]dsrbdteslto ntrsof terms in solution the described [Epe70] Eperson and [Tri69] Trigg Both When n > 4.79 ,tepofrqie nignosdvc called device ingenious an requires proof the 2, n h uzehsaslto fadol if only and if solution a has puzzle The see,an even, is oiotln fa 8 an of tiling Domino (a) n × n hsbadwtottoabtay1 arbitrary two without chessboard × or ihtomsigsursuigGomory using squares missing two with board 8 n seven. is n = n sbcueo h parity the of because ’s ooybarriers, Gomory (b) 2 , hsi biul true. obviously is this × qae of squares 1 named 187 Solutions  ...  

odd H’s T puzzle H_T ...  T 1 −  ... k T  1 T −  n ⇒  0 be the number of tails 1 ...... −  ≥ TH_HT n  H k T 1 coins: odd H’s H

... −  H n

T TT

k  1 tails followed by a single head (which ... T − ⇒ k ⇒ Domino Tiling of Deficient Chessboards  is even, are of the same color—for example, its  ...  n  T T

odd H’s times will remove all the coins. ... H_H ... n n   T 1 T 0 or can be removed as described above) and a shorter line −  ... TT k board, where = T coins. If the head is at one of the line’s ends (say, the left), its n n H H k  n

× ⇒ Gomory barriers used in the solution are not unique. Solomon n  The puzzle can be solved if and only if the number of heads (head-up TT ...  T ... odd H’s H

 T The second part of the proof—that if a coin line has an even number of heads Consider now the general case of removing the leftmost head in a line with If the single head is not at one of the line’s ends, its removal will result in two Let us first prove that this algorithm does solve the puzzle for a line with a single

TT is either empty if 113. Coin Removal two diagonally opposite corners (the in this book’s second tutorial)—no tiling isand possible black because squares the to numbers be of covered white are not the same. removal will result in the same kind of line with the puzzle has no solution—is similarof to heads the is proof zero, of the theremoved. puzzle first cannot part. If be If there the solved, number are becauseshorter only heads, line head-up then with coins an removing can even be any numberat of one least heads one or of of two which them having shorter an lines either even separated number yields by of a heads. one gap preceding the leftmost head. Whether that headhead, is its followed removal by will a yield tail a or line by with another an odd number of heads that is greater than 1. Let Thereafter, the puzzle can beshorter lines solved as shown by above. removing all the coins in each of these shorter lines with a single head at one of each line’s ends and a gap between them: Hence, repeating this step Solution Comments with an odd number of heads that can be removed by the same method: Golomb gave four alternative patterns“there are in literally his hundreds book of on others”squares [Gol94, of polyominoes, an p. noting 112]. that Of course, if two missing coins) in the initial linesolved is by odd. removing repeatedly If the it leftmost is head until the no case coins are for left. a linehead given, in the a puzzle line can of be

k  ...

T

Algorithmic Puzzles 188 nqeto.For question. in eeec oiscrua eso yD ekih[e9] h uzewsalso was puzzle The [Bec97]. Beckwith D. by version in included circular its to reference a example, the of for removal the solution: makes a heads three to that impossible. of tails lead line two note remaining the not from Also head may middle divide-and-conquer. coin the removing head-up from arbitrary help an unexpected removing somewhat gets it h o. ohHnyDdnyadSmLy ulse taotacnuyago. of century cases a about the it considered published Loyd also Sam outside and Dudeney “thinking Dudeney expression the Henry of Both source box.” the as the claimed often is it solution, the of FIGURE Solution Comments esml add simply we Solution Comments 2 n etcladoehrzna—ahpsigtruhtenx ounadrow and column next the through the of passing horizontal—each one and vertical one loih mlmnstedces-n-oqe taeybto up. bottom strategy decrease-and-conquer the implements algorithm emn ahtruhte( the through path segment osctv oeso trigwt 3 with starting 3 of powers consecutive 1.Cosn Dots Crossing 114. 1.Bce’ Weights Bachet’s 115. of issue 1955 his February in the Trigg Monthly in Charles published Klamkin by S. included M. was here given Quickies Mathematical case general The 329–332]. n .Ltu pl h reyapoc otefis e ntne fteproblem the of instances few first the to approach greedy the apply us Let a. h uzeapae nJ Tanton’s J. in appeared puzzle The h aeof case The − emn ahtruhthe through path segment 2 n 4.80 points. p 124). (p. iue48 rsnssltosfor solutions presents 4.80 Figure h nwr are answers The rfso twr’ aie fMteaia Curiosities Mathematical of Cabinet Stewart’s Professor A2 hl h anie scerybsdo h eraeb-n strategy, decrease-by-one the on based clearly is idea main the While fe h uzesisac for instance puzzle’s the After n n w − n = 2 = emn ahthrough path segment 2 = soeo h l-iefvrdpzls eas ftenature the of Because puzzles. favored all-time the of one is 3 1 oblnetefis rvosyuatial egto 2 of weight unattainable previously first the balance to 2 Ti5 rbe 6] iharfrnet h ouinby solution the to reference a with 261], Problem [Tri85, , ehv ouse to have we n − n osctv oeso trigwt 2 with starting 2 of powers consecutive 1) 2 n 2 onsb digt h atrtosegments— two latter the to adding by points onscnb bandfo 2( a from obtained be can points 0 w o at a n b,respectively. (b), and (a) parts for ov This Solve n n 1 2 = atc onsfor points lattice = n = n oblnewih 1 weight balance to 1 and 7 = ssle,tepath-construction the solved, is 3 3 Tn1 rbe 94,with 29.4], Problem [Tan01, , 4 n , n 5 and = mrcnMathematical American n Dd8 Problems [Dud58, 8 = . 3, hyso o a how show They Se9 .245]. p. [Ste09, n = . ,and 4, n For − 0 n 1) and n = = − 2 5. 2 n , . 189 Solutions , : n 1 l 3 3 − . − 1 = l n in the makes 1 7 n 2 l 21 + } + 1 2 7 ≤ between 1 111 9 l l − + n ≤ 1 4 3 + 2 3 6 − 20 13 111 enable weighing of ,... , 2, inclusive. A load’s 6 9 + + / 1 } 110 , 9 4 1 1) 0 1 − − = 1 n 3 n i − 5 , + 3 5 i (3 + 1 different subsets (less if some 101 12 12 110 2 4 9 − − = ,... , = i 9 contains only 0’s and 1’s, the load n 1 i 3 , , w 1 4 4 1 2 0 0 { 100 / − = 1 i n − = 1) 3 4 + 11 11

i 1 102 the single weight still has to be 1, of course. − 3 allow to weigh any integral load + , , contains one or more 2’s, we can replace each i 3 n + } 11 l 1 9 3 4 2 (3 , = 1 = 2 which yields the weights needed for weighing ≤ n , i 3 3 , + 10 10 l l 1 2 2 w 101 10 { 1, inclusive. The fact that every integral weight { 9 , l For − . 1 1 1 1 n 1 weights there are only 2 9 9 2 2 2 ’s binary expansion indicating the weights needed for load − n l 100 > 3 1 can be balanced with this set of weights follows immediately enable weighing of every integral load up to 4. The weights l = can balance every integral weights up to their sum 3. For n } i } − 1 3 2 2 n , 1 8 1 1 1 , 0 − 2 1 22 − 1 { = 9 i n { ≤ l l l

the set of consecutive powers of 2 The three weights enable weighing of every integral load up to 13, as shown in the following l . ≤ n } weights for 4 9 1 different loads can be measured with them. This proves that no set of n , in binary 3 =

weights for load load l − In general, the weights Since for any set of Generalizing these observations, we could hypothesize that for any positive b. If weights can be put on both pans of the scale, a larger range can be reached , 3 n

1 and their sum 7, with of the weights are the same) that2 can be put on one pan of the scale, no more than it possible to balance everytheir sum integral load in the largest possible range from 1 to requires putting the weights correspondingbalance. to If the the 1’s ternary expansion on of the opposite pan of the integer The weights expansion in the ternaryternary system expansion indicates of the load weights needed as follows. If the every integral load from 1 to their sum from the binary expansion of with if weights can be put only on the free pan of the scale. weights can cover a larger range of consecutive integral loads than 1 range1 table: { The weights in the spirit of greedyw thinking, we take the next previously unattainable weight:

l l

in ternary in ternary

weights for load l load weights for load load l Algorithmic Puzzles 190 o egigapstv od aigit con h ymty hywl eal to able be (3 will than they more symmetry, no the weigh account into Taking load. positive a weighing for n nerlla rm1t 0 nlsv:teee od 2 loads even the inclusive: 80, determine can to 54 1 and 18, from 6, load 2, weights integral integral four each same any the the of with example, determined balancing For be weights. exact can of loads an integral number if many than as that twice other required, out not systems pointing is load numeral worth also of is usefulness It occasional decimal. and approach greedy the a,o o u nete fte.Hne hr r 3 are there Hence, them. of either on put not or pan, Comments that 2’s.) proves the This all eliminate one. to starting able representation the be of will the we left Using replacements, the such to of number position finite some a at after rightmost be new the will simplification, any, a after if 2, 2, rightmost the with start we if that (Note example, For 2by(3 Solution load ubro ’ ntebnr ersnaino 2 of representation binary the in 1’s of number Problèmes its in 12, load 95]. than p. lighter the 7.L.3, but Section 10 overweight [Sin10, than 11 and heavier obviously is is underweight weight load that integral an 54 if example, and For 18, consecutive question. two 6, finding 2, by determined of is combinations load odd any whereas exactly, balanced 1.BeCounting Bye 116. 7.L.3]. first and the 7.L.2.c Sections as [Sin10, (1202) problem the Fibonacci solved and who mathematicians (c.1075) Tabari recreational Hasib of history considers in research mathematics Modern it. to solution a contained which 1612, in a oe agrrneo osctv nerllasta 1 than loads integral consecutive of range larger a cover can p 207–208]): pp. a ftesaeadalteweights the all and scale the of pan h uzei ae fe lueGsa ahtd éiic h uhrof author the Méziriac, de Bachet Gaspar Claude after named is puzzle The ial,aywih nastof set a in weight any Finally, l ypaigalteweights the all placing by 5 − = = Bc2—h ineigcasci erainlmteaispublished mathematics recreational in classic pioneering [Bac12]—the )t represent to 1) (3 12 h nwr opr a s2 is (a) part to answers The 3 h uzepoie odeape fascesu plcto of application successful a of examples good provides puzzle The − = 1) 1 · · 3 3 l 1 n 1 = − − + l

n 1) i 1 l 2 = − = nqeyi the in uniquely · 0 / 1 · 3 ifrn od.Ti rvsta ostof set no that proves This loads. different 2 3 β

w 0 n 0 i 3 i = egt a epto h etpn ro h right the on or pan, left the on put be can weights = n i i = = − , w 0 1 1 1 i where 3 β · = i · 3 i o negative for 3 3 2  3 1 i log , i − + o positive for β where 2 aacdtraysystem ternary balanced i 1 n (3  ∈{  · log − 3 − 1 0 2 n β , n 1) − ; β  i 1 h nwrt at()i the is (b) part to answer the i − , ∈{ n 1 saogwt h odo one on load the with along ’s · − β 3 − n · i 0 . 1 3 so h poiepan. opposite the on ’s 0 ast use to ways 1 } 0 = , . . 1 ≤ , 2 , − l · 4 ≤ 3 1 .., ,... 1 } ecnweigh can we , (3 − se[Knu98, (see n 1 − 0cnbe can 80 · n n 3 1) fthem of weights 0 / 2 . 191 Solutions . . ) 6 9 1 0, 1 < n − ( − and − = 2 k k = B 2 k 2 4 − where k 2 1 2 10 , ≤ = n − = − − 2 winners 2 n 2 ) and / 0 n − 4 / k ) ) 2 2 2 k b (9) < b is odd in this 2 b 1, 2 . = = 2 ≤ − − n 0 = − b n n n = k ) for any positive ( ) − = and hence 2 n − n 2 n < (10) k ( + k ( b n 1 If 2 b 2 rightmost binary digit. b G (1) . − k ) is the number of players. B = < n n = it computes ( ) ) n , B , n ) n , 9 2 ( n ( and hence 2 the number of byes is equal to b < ( b = k , G 1 2 sa0asits n , where = − . (Note that 10 k k  ) can be computed by counting the ≤ 2 n 2 0 is even 1isodd n n Since = ( ) satisfies the recurrence equation and n 2 . ≤ n B − > > n 1 ( ): 1 < n 2 n n log + G n n Thus, we have the following recurrence for − 1 ). Hence ( k . < n − B 2 2 ( = ) is equal to the number of 1’s in the binary − k 1 / this algorithm computes b 1 )if 1 − k = , 2 1 + k 1) − n 2 +  k )if 10 ( n 2 + n 2 n 2 ( G (  n = B players play in the first round, with ( [Gar78, p. 6]: = ( B b n b , where + ) n For example, for = 1 1 − . 2 is even in this case, it ha 2 + − n n / n n Indeed, let 2 k  ( − 2 . 1) ); we will show that b  − 6 k the number of 1’s in the binary representation of 0, is equal to 0. n 2 = − , k 2 aha!Insight = In other words, the number of byes as defined in part (b) is equal to = 2 n b ≤ log ( ) . . By definition, ) be the number obtained by Gardner’s algorithm for a positive integer (1)  and therefore yields 3 byes.  n 1 = n n 10 be the number of players in the tournament (2 G ( 2 n + ( − ) n − B k 2 be an odd integer greater than 1; 2 < G n and therefore yields 2 byes, whereas for 2  ( n 111 1 . 2 b be a positive even number; 2 log 10 n − ≤ 2 = k n players get a bye, 1 b. Let So let a. The number of byes, defined as transfers of the fewest players directly to the Let 7 110 log b = (2 2  + n n be the total number ofso byes, that defined there as is transfers of annumber fewest even of players players number is in of even, there each players are round is no in byes odd, each in one that round. round; of In if them the otherequal number gets words, to of a 1 players if bye, the making the number of players in the next round representation of Since 2 therefore is even as it should be.) initial condition given above for the number of byes this definition of the number of byes and hence If second round so that theis number equal to of 2 players left for that round is a power of 2, has the same number of 1’s as advancing to the second round. Thus, we have the equation the number of 1’s in the binarypart representation (a). of For the example, number for of byes as defined in k even = = While there isrecurrence, no it closed-form can be (i.e., obtainedGardner by direct) in the his formula following algorithm, for mentioned by the Martin solution to this number of 1’s in the binary representation of the difference Its solution is Let Therefore, Algorithmic Puzzles 192 to oraeta iieb-afagrtm n a e nte ouinb adding by solution another get 2 can One algorithm. divide-by-half a as tournament Solution Comments odd any for Hence, 2 of representation ha it case, hsi civdb up ftefis,ls,adte ihro h w remaining two the of either then and last, first, the of pegs: jumps by achieved it this 1 Without respectively. pegs, without and that assume with may we cells generality, of represent loss 0’s and 1’s where 1.OeDmninlSolitaire One-Dimensional 117. [Knu98]). e.g., (see, science computer in applications have trees October the [MathCentral], (see month). tournament the of the problem in 2009 players real of number the is rtmove first 2or5). igepgo h or;if board; the on peg single a fpritdjms hc ses opoeb nuto on induction by prove to easy is which jumps, permitted of enee oshow. to needed we h left, the ys hc stenme f0si h iayrpeetto of representation binary the of in numbers 0’s the of for number the formula is alternative imaginary which the the byes, to between leads games approach of This number players. the real counting and by obtained then is byes of n  − ≥ log 110011 n iial,if Similarly, If ytewy eodterueuns o oraetognzto,tournament organization, tournament for usefulness their beyond way, the By If h ouinflosfo netgto fteptenta rssatrany after arises that pattern the of investigation from follows solution The h mt ela h tr a ei oain r5(symmetrically, 5 or 2 locations in be may start the at cell empty the , ) n h eann e a n pa either at up end may peg remaining the and 4), 2 essprtdb mt el ilremain. will cells empty by separated pegs 2 l l n = =   − r and 2 and 0 / n sa1asits 2 suigta h or’ el r ubrdcneuieyfo 1 from consecutively numbered are cells board’s the that Assuming mgnr lyr ogtasmlrisac ftepolm h number The problem. the of instance simpler a get to players imaginary ⇒ ≥ (2 u ouint at()i ae nitrrtn single-elimination a interpreting on based is (b) part to solution Our l r r = k essprtdb mt el ilremain. will cells empty by separated pegs 2 ≥ = − and 1 k 001011 n vn l h esbtoecnb lmntdb series a by eliminated be can one but pegs the all even, and 2 n 2 − n , − ihms iaydgt rpigta at1i h binary the in 1 last that Dropping digit. binary rightmost > n fe h nypsil upb h atpg twl remain will it peg, last the by jump possible only the after r 1) ilstebnr ersnainof representation binary the yields 1 ≥ / , 2 eget we ⇒ 1 l = , = after 1

2 and 0 k ...  − 001100 l G 1  l ( r 1  − / n ≤ 001 2 r ) ( 

r > n = . oployjmst h left, the to jumps compulsory ...  + r 2 1 ⇒ , 1) 1 +  after / G 2 n ( ihr000 r000010 or 010000 either = − n  + 2 r b 1or / 1 2  )  , n n hc seatywhat exactly is which oployjmsto jumps compulsory + 2 − r n ned if Indeed, . 1 − (symmetrically, 4  1 . , where  n r r − / n 2 = > 1or + . 2 1 , 193 Solutions  1 .  2 1 to a single peg, 2 − ,  ... r − 2  ... r 2 pegs to the same

> > r r 0011001 001100 1  1 2 pegs to the right of them can , where 2  1 −  l ... ⇒ > 1 r r ...  to a single peg—the one described  1  1

r ...  r ⇒ ...  Winning Ways for Your Mathematical Plays

... 001011 it is impossible to reduce the position to a single peg. , ⇒ l ⇒ ≥  1  1 r r ... r  2 pegs to the left of 00 nor ... 

>

2 pegs, which proves the inductive step: 2 and l 0011 − The main tool in solving the puzzle is the decrease-and-conquer  > r 11 l 110011 The minimum number of moves needed to solve the puzzle is 16. l  ... 1

As explained in the book’s first tutorial, the initialThe graph state can be of unfolded as the shown in puzzle Figure 4.82: can move vertex be 8 up and vertex To achieve the puzzle’s objective, one of the two black knights at initial Finally, if The puzzle is a one-dimensional version of the old but still popular game played pattern with be reduced to a single pegpeg without can “help” be from brought a in peg withbut from a the pegs the jump on from other both the side. sides can other Such not side a be over reduced to the a neighboring single peg, peg in this fashion: conveniently represented by the graph in Figure 4.81. 5 down to get thethe first second figure figure; there; swap swap the themove locations locations vertex of of 11 vertices vertices up 4 10 and and andpuzzle’s vertex graph. 6 12 2 to to down get get to the get third the one; unfolded representation ofpositions the 1 and 3 hasconsider to the knight move at to 1 moving either to 12Taking 12, which or the is 10. closer shortest than Without path, 10 loss to itneed its of at will initial generality, least position. take 4 we moves 3 total moves. to get The from other their initial two positions black at 2 knights and 3 will to their goal there is just one way to reduce 110011 Indeed, neither above. Solution Comments Moreover, since it is impossible to reduce 011 The same first two jumps reduce the position with an even 118. Six Knights [Ber04], not to mention several websites devoted to it. strategy. Using the same approach, oneodd can number also of show that cells the that only hasor board a 3. with solution C. an Moore is and of D. size Eppstein 3,that [Moo00] can gave with arise a the in formal empty this description cell game. of all either positions at 1 by the same rulesgame’s on history two-dimensional and boards. winning strategies, ForD. see, Beasley an for [Bea92] in-depth and example, Chapter account the 23 monograph of in by the John Algorithmic Puzzles 194 FIGURE FIGURE n5o oemvstettlnme fmvswl ea es (5 least at be this does will it moves if of and number moves total 4 the in moves this do more cannot or it 5 because will in moves 1 that at 3 moves knight in black of 12 the sequence, reach sequence a to such a have In is moves. which 16 there however, than less that moves, in puzzle 15 Assume the or contradiction. solves 14 by in prove done to solved be easy be cannot cannot is This puzzle moves. the 14 Thus, than positions. fewer goal in for their moves reach 7 of to bound knights lower white same the the implies symmetry The 11. and 10 at positions oe xed1.Bttepzl a esle n1 oe,freape hs in those example, for moves, 16 in solved sequence: 11 be following of at can the number puzzle knight necessary the the white making But the thus 15. and by exceed 1 preceded moves at the knight be by black must the preceded blocking which be must 6, 11, must to which to move which 9, move 4, to to 3 move move at 2 10 knight at at black knight knight must black white 12 the the at by by knight white preceded preceded the be be 7, must to which 6 from 2, move to can go 1 in knight black the before But 1 7 4 1 0 B B (2 (1 1 5 4.82 4.81 8 2 1 − − 6 9 rp ersnigpsil oe nthe in moves possible representing Graph nodn ftegahi iue4.81. Figure in graph the of Unfolding − − 1 9 6 3 2 7) 10) , , 1 W 7 6 1 0 B (11 (7 − 1 5 − 2 8 1 6) 6 , − 10 7 W 1 4 1 9 4 3 1) 2 (12 , B 11 − (3 2 8 5 1 7 6 1 2 7 − − 4 12 2) 9 6 3 − 1 5 8 2 1 , 11) B i Knights Six (6 , 1 3 9 4 − 0 W 4 7 1 7 (10 1 0 − puzzle. − 1 12) 7 6 2 1 9 + . − 1 4) 8 2 5 4 1 1 8 5 2 1 + − 7 3) = 1 , 3 9 4 0 1 6 3 16. 2 9 195 Solutions , 2 = n , discussed 2 board, and one × Guarini’s Puzzle [Gra05, pp. 204–206]. 2 board, one white tromino in the published two papers with incorrect × 2 board with the missing square. Then 4 board with four possible locations of a × × 2 board (see Figure 4.83). × 2 boards and place one gray tromino to cover the The New Puzzle Classics × 2 board, one black tromino in the lower right 2 The puzzle is a well-known extension of × Colored tromino tiling of a 4 The puzzle can be solved by the following recursive algorithm. If Journal of Recreational Mathematics 4.83 alternating sequence of two black squares followedsquares, by with two the white missing square possibly replacingsequence. one square in this sequence of two white squares followed bythe two missing black square squares, possibly with replacing one square in this sequence. alternating sequence of two black squares followedsquares, by with two the white missing square possibly replacingthis one sequence. square in sequence of two white squares followed bythe two missing black square squares, possibly with replacing one square in this sequence. Note that for any location of the missing square, the following properties hold: The • Going down, the right edge of the board is covered by an alternating • Going right to left, the lower edge of the board is covered by an • Going up, the left edge of the board is covered by an alternating • Going left to right, the upper edge of the board is covered by an place one black tromino in the upper left 2 missing square (marked by X). white tromino in the lower left 2 upper right 2 three central squares that are not in the 2 FIGURE divide the board into four 2 Solution Comments in the tutorial on algorithm designrepresentation strategies. change: The first, principal the idea board is in represented both byis puzzles a unfolded graph is to and then give the a graph clearer picture of the task at hand. 119. Colored Tromino Tiling answers to this[Dud02, problem Problem in 94] 1974 consideredno and the move puzzle may 1975 put with two [Sch80, an knightsFor of pp. additional other opposite variations, constraint color 120–124]. see in Loyd’s that a Dudeney “Knights position Crossingpp. over to 57–58]) the attack and Danube” each Grabarchuk’s (e.g., other. [Pet97, Algorithmic Puzzles 196 o h etotbx Let box. leftmost the for 0 a 2.PnyDsrbto Machine Distribution Penny 120. [Chu87]. Johnsonbaugh of illustration excellent an here have we strategy. tutorial, divide-and-conquer first the the in discussed was which h ahn’ itiuinof distribution machine’s the nmrtdaoermi ai nec trto fteagrtm hc a be can which properties algorithm, the the induction. of mathematical that by iteration fact checked each easily the on on valid based remain is above correctness enumerated algorithm’s the of proof The FIGURE Solution Comments ytesm loih sea xml nFgr 4.84). Figure in example an (see algorithm same the by banteformula the obtain hte the whether stenme ftels o ihapny hsci a bandb replacing by obtained was coin This penny. a with box in box coins last two the of number the is rmn ocvrtetrecnrlsursta r o nte2 the in not are that squares central three the cover to tromino pligtesm esnn oaybox any to reasoning same the Applying ihtemsigsur.Te ieec ftetre2 three the of each tile Then square. missing the with mre yX). by (marked If ohtepzl n t ouini rmapprb -igCuadRichard and Chu I-Ping by paper a from is solution its and puzzle the Both n > 4.84 2 , .W sueta h oe r ubrdlf orgtsatn with starting right to left numbered are boxes the that assume We a. ooe rmn iigo 2 a of tiling tromino Colored i iietebadit or2 four into board the divide hbx 0 box, th si a h aefrtetln loih ihnnooe trominoes, noncolored with algorithm tiling the for case the was it As k − ,wihi unrpae orcisi box in coins four replaced turn in which 1, ≤ i ≤ n k b , ene,where pennies, 0 b a ono o;i particular, in not; or coin a has 1 n ... =

b i = k k i 0 n eabtsrn ersnigarsl of result a representing string bit a be ihaci ntefia itiuin we distribution, final the in coin a with − b 3 i 1 2 × i × . b 2 i 2 3 seult r0dpnigon depending 0 or 1 to equal is n − n or ihamsigsquare missing a with board − 1 1 orsadpaeoegray one place and boards × 2 n − 1 n orsrecursively boards − k b 1 − k × = ,ads on. so and 2, 2 ,where 1, n − 1 board k 197 Solutions . , i  b . 1) 1 + − n i ( 2 2 , = i log 1 is equal to b i 1) 0 . + Since the binary k = = 0 i

. − 2 1 i = − + pennies is equal to the (2 n 2 + n 2 n (0) + 1 = because if the egg breaks, 2 C 0 + i k · + b , . According to the answer to i log 3) 2 k 0 n  2 k = i

− + ≤ = i i in reverse order ( − 1 2) ’s binary expansion, which serves as i C < n n 2 3 − i which is 2 i b , ( 0 n = C k = 2 i

1 irrespective of an order in which coin pairs 1 for 0 +···+ 2 , 2 + = n + = − 2 i 1 1) 2 1) + + − + − i 1) 1 i 1) ( : − i (2 i i + C 2 1 + b be the binary expansion of 2 1 floors will need to be tested sequentially starting with the 0 3) 0 + + k 2) = = b 1) to be prepared for the possibility that if the egg breaks, each i )

− − i ) 1) − i i k − ( ( i ... = − ( − k 1 C i C ) ( i i ( C − The puzzle takes advantage of ( ( (2 k C + C i 2 b C We have the following recurrence for the number of iterations needed The answer is 14. i k ) be the maximum number of floors for which the problem can be solved 2 2 2(2 2 ... k . b b k k ( 0 = = = = = k = H ≤ ) i

i i drops. The first drop has to be made from floor ( C k c. Let b. The minimum number of boxes needed to distribute Let ≤ number of bits in the binary expansion of part (a), when the machine stops, the number of pennies in box 121. Super-Egg Testing an invariant here, and backward thinking.invented It by is James Propp a (see minor [MathCircle]). modification of a problem are processed. expansion of any issame unique, coin the distribution machine for always a ends given up with the first floor. If the first drop doesfrom floor not break the egg, the second drop has to be made to place one penny in box Solution Comments which is the difference between thenumber of number 1’s of in pennies its binary given expansion. at the start and the Hence, the total number of iterations made byfound the as machine before stopping can be Solving the recurrence by backward substitutions yields the following: 0 In other words,expansion the of bit the string initial number of of the pennies final distribution represents the binary in each of the lower Algorithmic Puzzles 198 au of value h alaetrasi hc vr alaetra a omr hnoeenemy one the than chamber. more same Hence, the no one. in has parliamentarian by by every least which decrease in than at parliamentarians will more decrease the no chamber will after old pairs terminate his enemy will of in algorithm new number pairs the total enemy in the of enemy two, one number than the more in and no enemies Since chamber have chamber. two will other least parliamentarian the at into transformed has parliamentarian the who this parliamentarian same transform the a chamber, in same is currently the there are as who chambers long both As Let in chambers.) chamber. pairs the enemy of between number equally total about the them divide example, (For way. enemy one than chamber. more her has or parliamentarian his no in that way a such in chambers two into h trtv mrvmn taey hc sotie ntebo’ rttutorial. first book’s the in outlined is which strategy, improvement iterative the Pacification Parliament 122. Peter example, for see, popular: [Sni03]. Sniedovich quite become has Winkler’s puzzle this 166], Problem egg (the the operation basic finds its it times of backward: executed. number is case given drop) a worst for the problem the analyzing of in size largest unusual rather is it approach, Comments for formula same the get can one (Alternatively, the of Comments Solution sntuiu:tefis rpcnas eeeue rmflos1,1,1,ad10, and 11, 12, 13, floors course. from of executed drops, other be the also of adjustments can corresponding drop with solution first This the it one. tested unique: until successfully 100 not last consecutive the and is each after 99, from floor dropped 95, next be the 90, to with 84, is starting egg 77, floor second 69, the 60, happens, this 50, if 39, and 27, breaks, 14, floors from dropped be oml for formula nrpaigti ruetfrteremaining the for argument this repeating On H ( htrmist edn oase h uzesqeto st n h smallest the find to is question puzzle’s the answer to done be to remains What tr ydvdn l h alaetrasit w hmesi narbitrary an in chambers two into parliamentarians the all dividing by Start fe t pernei h okb oehKnasre l [Kon96, al. et Konhauser Joseph by book the in appearance its After k ) = k − k k ahmtclMind-Benders Mathematical uhthat such or rmfloor from floors 2 + h nwri tu” h olwn loih ildvd h parliament the divide will algorithm following the “true”: is answer The H H ( n a osdrteagrtmsligtepzl sbsdon based as puzzle the solving algorithm the consider can One greedy the on based clearly is puzzle the solving algorithm the While k ( ): H k − ( k k ) )for 1) ( = k + k k + 1) > k ( / k 2 + 1 − , ≥ oflo 2 floor to 1 H 1) 100 (1) +···+ Wn7 .1]adapprb Moshe by paper a and 10] p. [Win07, . = hsvleis value This 1 . k p k ) − trtos ihafia atto of partition final a with iterations, − 1 edt etse sequentially. tested be to need 2 H = rp,w bantefollowing the obtain we drops, 2 ( k k ( ysligterecurrence the solving by ) k k + = 1) 14 / . 2 . h rtegcan egg first The p be 199 Solutions 1) . n clips + k ≥ k 1 2( − The second = 1 . 1 1 + k + + k should be of length 1)2 2 1) , 3 + = S + k k 1) A Discipline of Programming all blue + k ( 1 pieces. The shortest of them, by S. Savchev and T. Andreescu + + removed clips, it will enable us to such that ( k k k k , a Russian popular science magazine in unknown Kvant is a given positive integer. If we remove The third shortest piece, k . 3 all white + k 4 Mathematical Miniatures = all red should be one clip longer, that is (2 1) , 1 clips long: together with + 2 S single clips, where k + Both the problem and the algorithm were proposed by W. H. J. the maximum length of the chain for which the problem can be solved k k 2( , The answer is the smallest integer The following algorithm is based on considering the checker row as ) k + ( 1) max n + must be As suggested in the hint to this puzzle, it is easier to reverse the question and find The earliest reference to the puzzle we have been able to find is Problem M580 k , 1 first S shortest piece, physics and mathematics for school students andsuch teachers. books It in was English as later included in combine them in a chain of any length from 1 to clips long. With it,(2 we will be able to make a chain of any length from 1 to Solution Comments Initially, the red, white, andin blue the sections unknown are section. empty, On withunknown each section all iteration, by the one the checkers element algorithm being either shrinks(i.e., from leftmost) the the checker left size in or the of unknown from the section theafter is right: the red, If swap red the it section with first and the advance firstnext to checker checker; the if next it checker; is if blue, swap itan it is illustration with white, in the advance Figure last to 4.85.) checker This the before step thethe is blue unknown repeated section. section. as (See long as there are checkers in Solution 123. Dutch National Flag Problem [Sav03, p. 1, Problem 4]. A detailed discussion of this strategy, along with severalit, important can algorithms be using found in A. Levitin’s textbook [Lev06, Chapter 10]. (p. 38) in the August 1979 issue of by removing 124. Chain Cutting Feijen; it was madeprominent computer famous scientist, by in inclusion in his computer book [Dij76, science Chapter 14]. The circles colorful name by of the problem Edsgerboth has an Feijen obvious Dijkstra, explanation: and a Dijkstra wereDutch Dutch, national flag. and red, white, and blue are colors of the made up of four contiguous possibly emptywhite sections: checkers, red then checkers on the the checkers left, whose then colorsblue are checkers: yet to be identified, and finally spread along the chain, the chain will split into Algorithmic Puzzles 200 FIGURE 4.85 he ae fteagrtmfrthe for algorithm the of cases Three is nnw hce swhite is checker unknown First unknowncheckeriswhite is nnw hce sblue is checker unknown First unknowncheckerisblue is nnw hce sred is checker unknown First unknowncheckerisred ? ? ? ? uc ainlFa Problem Flag National Dutch ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? . 201 Solutions ), we k ( , 1) 3 single ˜ S − max k n of length 1 , + 1 < k 1) . + n k + S 20 ≤ 1)(2 k ( k removing = k 11 can be obtained + , 2 ) k |+ 11 k = ( in the above solution. k ( S 1 2 + + |+ 1 single clips are removed max k + k 3 n S ˜ S ) 6 | − th single clip can be removed k +···+ = chain pieces formed as above, ( k = k + ) k k 1) n such that 1 be the length of a chain given. 3 9to 2 max |+···+| the k n 1 + > = , S k k | the solution just described requires |= n 2 ≤ ( 3 , 2 ˜ n S 2 2 | |+ |+ k 2 < S +···+ + = S 1 pieces, we will be able to get a chain of any 2 k 1) X 2 1) + , and 2 single clips; hence, together with |+| − k + + 2 1. From the preceding discussion we know that at 1 S k k 2 S . ), inclusive, where ( | , − k 1 1 2( 1 + X ( S |+···+| + max 1 and so on, until we get the longest piece, − + k n we can form a chain of any length between 1 and 23, S , 1 clips as explained above is, in fact, sufficient to achieve our max | , n + k 1)(1 1) 1) 1)2 2 k < 20 and hence denote the lengths of the first + + + + will be shorter than the last piece n | = k k k 1)2 , k k = ( ( ( 1 ( k S < 2 | + n + 2 + + k = k 1) ˜ S k k ( ) = k − (This assertion can be formally proved by mathematical induction.) 1 ( = = = X . ,... , k | removed clips and these ( + ) 1 1) k k max S X single clips must be removed from the chain to solve the problem. Now we ( | n 3) max + k n + k max If Now, to return to the puzzle as stated, let k ( n k 1234567891011121314151617181920 2 where as a combination of some of clips as described above solves the problem. If But it is easy to see thatFor this partition example, of the if given chain will still solve the problem. will show that removing goal, with a minor adjustment explained below. If removing clips 4 and 11: can also obtain a chain of any length from from the right end of the chain given, while the first where integer length from 1 to as illustrated in the following diagram: least the last piece, Obviously, there exists a unique positive integer Having A chain of any length from 1 to For example, for (4 1234567891011121314151617181920212223 Algorithmic Puzzles 202 h eea hoe httesrigof from follows sorting also the it less that directly; in this theorem the prove done general for to be the difficult place not cannot is appropriate comparisons (It an by comparisons. five numbers find than four then Sorting and them. first among weights fifth four sort idea: fruitless 2.Srig5i 7 in 5 Sorting 125. bibliography Singmaster’s D. see references, related few traveler the a 5.S.1]. week Section the For [Sin10, of inn. day every the for owner at inn’s an stays to pay to cut to needs traveler design. algorithm for strategy greedy the he egig adteasmto made): assumption the (and weighings three tm n ,adies3ad4 ihu oso eeaiy emyasm that assume may we generality, of loss Without 4. and 3 w items and 2, and 1 items hti,compare is, that Solution Comments 10. to 5 from length any of chain a obtain also can we to 1 from length any of chain A if example, For above. as positions same the at hrfr,wt ols fgnrlt,w ilcnie nyCs sthe the as represent to 1 above, Case mentioned only as consider helpful, will is weighings. It we two two. generality, first the the of played in of roles loss participating representative the weights no in of only with pair differ they second Therefore, since and 1 first Case the to by analogous is 2 Case Clearly, 1to5.Let a that is failure this completely from are them conclusion of four The sorted. before numbers five all line.) involve must real algorithm the desired on sorted the points considers one as if requires clear numbers especially numbers is sorted (This four comparisons. among more number three fifth least the at of place proper a find to that eursa least at requires obnto fsm of some of combination ob eoe r tpstos4ad10: and 4 positions at are removed be to 1 h otcmo eso fti uzei hto ee-ikgl hi hta that chain gold seven-link a of that is puzzle this of version common most The eei nagrtmfrsligtepolm re h tm rirrl from arbitrarily items the Order problem. the solving for algorithm an is Here < w 2 and ti epu osatwt re netgto fantrlbtultimately but natural a of investigation brief a with start to helpful is It w 1 w h bv ouin(.. Sh0 p 2–3] ieyillustrates nicely 128–130]) pp. [Sch80, (e.g., solution above The .., ,... 3  w log < 2 12345678910 w ae1: Case ae2: Case and 2 w 4 n 5 . ! eteukonwihso h tm.Satb weighing by Start items. the of weights unknown the be eg h eve tm on ntefis w weighings, two first the in found items heavier the Weigh S w 1 oprsn ntewrtcs. ute,i ses osee to easy is it Further, case.) worst the in comparisons 4 n igecis ec,tgte with together hence, clips; single 2 and . w w w osbecssmyaiea h eut fthese of results the as arise may cases possible Two 3 1 < < X w w | S 4 2 1 |+ < < n w w 2 rirr elnmesb comparisons by numbers real arbitrary 4 2 = and and n 3 = + w w 0adhence and 10 2 1 3 < < = w w a eotie sa as obtained be can 5 2 4 . X , k S ˜ = 2 flnt 5 length of 2 , h clips the , 203 Solutions ; , , If 5 2 2 < < . . . . . w ) ) w w ) ) 3 1 5 4 4 4 4 w w w < < w w w w > hence, 4 < 3 ; 3 < , we will 4 w 5 5 w w and 3 w w w If . w on the sixth 3 < . ) ;if 2 w In the second < 2 as the seventh 4 2 4 w , w w w w and 3 . 2 4 w 1 > w < < w w and 2 3 1 as the fifth weighing The Art of Computer < is to the left of is to the left of is to the left of is to the left of 3 < w w we obtain w , we obtain 3 3 3 3 3 w , 5 2 as the seventh weighing < 5 , w w w w w < w w , 1 ( ( ( ( 3 w 1 3 If on the fourth weighing. As w 4 4 4 4 w < . w < w 2 > 2 w w w w 2 5 w < < w > is to the left of 3 w w Finally, if 1 < < < < 3 3 3 w > . w If w 3 3 3 3 < w w 5 5 and w w w w 3 ;if . w < If w 3 4 2 w . 5 w w w < 1 we obtain w and and and and < w 4 , (point < 1 1 w 2 4 and w w to obtain one of the two situations: − − − − w w < 5 and 4 5 4 4 4 < w 2 . 3 w w w w w < < 4 3 w . w as the seventh weighing compare 1 3 w 5 − w − − − we obtain , w < w w , 1 5 4 2 2 with < If 2 3 w < w w w w . 5 3 < w w we obtain 1 5 w and w 4 , − − < − − w w 1 < < w 2 2 1 5 3 < w 1 3 < w w w w w 2 < − w w and 3 w 3 > If 4 − − − − 3 w to obtain one of the two situations: If w . 3 w 1 1 5 1 . < w 1 1 2 w w w w w 1 < w w − w w 2 2 Similarly, if on the sixth weighing − − − − ;if w The puzzle presents a well-known problem in sorting small-size files. . [Knu98]. In particular, he gives a very elegant diagramming way to w 4 < 4 : : : : and with and we obtain w 5 1 1 4 4 < A fair solution for two people is to let one of them cut the cake in two w − 3 , 5 3 we obtain w w w w w 1 1 w 1 < w w , < w w 5 w 5 < > < > 2 w w − w 5 5 5 5 Person 1 cuts off a piece X of the cake. He will have an incentive to make it > . w w w w 3 < < < n Now we consider the situation that arises if As the fourth weighing, compare w If If If If 2 3 1 we have situation, as the sixth weighing also compare compare weighing compare w give further comparisons only for the firstcompare of these situations. As the sixth weighing the fifth weighing, compare if weighing, no seventh weighing is necessary since we know that compare Solution Comments as the seventh weighing compare w In the first of these situations, as the sixth weighing compare we obtain w Since these two situations differ only by the relative order of numbers involved in sortingcomparisons as indicated above, points we have on the following the diagram: real line. So, after the first three 126. Dividing a Cake Fairly Donald Knuth discusses it in SectionProgramming 5.3.1, Volume 3, of his present the above algorithm discovered by H. B. Demuth (pp. 183–184). pieces and let the other choose his piece.can For more be than generalized two people, as this follows. procedure to First, all the persons are assigned numbers from 1 Algorithmic Puzzles 204 rtvstn qae ntetootrlyr ftebad upn ooeo the of one to jumping try board, will the we of precisely, layers More outer board. two is the the that of in square edge squares unvisited nearest visiting an the first to to move possible always as will close square We the as at 4.86. it finish Figure and in board the 64 of corner numbered left upper the at tour knight’s the start 2.TeKih’ Tour Knight’s The 127. Jack by monograph the in them [Rob98]. find Webb William will and Robertson reader variations interested its for The as different well extensions. by as several and problem given then, original the was Since for people suggested 1944. been three in have for algorithms Steinhaus extension Hugo its mathematician and Polish years, the 2800 for known been has Solution Comments X that believes he if X, of slice a off 1/ by cut decreased than to be larger option likely an is will have piece will the 2 larger, Person it others. makes the he if piece, this getting up end 1/ to close as FIGURE 1/ than larger is X that 3 Persons believe nothing. not does 2 Person If cake. w epeaelf,te iietermiigpr wt l h xr lcs yone by slices) extra choosing. the just other all When the (with and X. part cutting adjust remaining person to the added divide any, they if left, slices, are people extra two the all includes which cake, the of rdigntig hntels esnt oc ae tfrhmef n the and himself, for it takes X touch to person last remaining the Then nothing. doing or X codn oInSeat[t0,p.45,teaoeslto o w people two for solution above the 4–5], pp. [Ste06, Stewart Ian to According 4.86 n eas ftebadssmer,w a,wtotls fgenerality, of loss without can, we symmetry, board’s the of Because ngtscoe oro tnadchessboard. standard a of tour closed Knight’s − n h loih scerybsdo h eraeb-n strategy. decrease-by-one the on based clearly is algorithm The ho h aea osbe fh ae tsalrta ht emight he that, than smaller it makes he if possible: as cake the of th esn pl h aepoeuet iietermiigpart remaining the divide to procedure same the apply persons 1 n 26 41 14 11 36 39 16 ho h ae n d h lc otermiigprino the of portion remaining the to slice the add and cake, the of th 1 , 4 .., ,... 10 38 13 25 15 64 35 40 n 56 17 27 37 xriei untesm pino ihrdecreasing either of option same the turn in exercise 42 12 63 2 57 24 54 49 60 51 34 9 62 28 43 52 55 59 18 3 48 58 33 61 50 23 53 8 44 21 46 31 19 29 4 6 n ho h ae edoes he cake, the of th 32 22 30 20 47 45 7 5 205 Solutions closed switch 1 2 13 − n 1) − ( 1 6 − n 2 and denote the “on” and 3 2 n discussed in the first tutorial and : logical rules of thumb that may problem is a special case of trying to heuristics is one of the two most studied puzzles involving Queens Problem Knight’s Tour - n 0. Hence, to begin with, we need to turn off the last ... 8 board, it is surprising that finding even one of them with y a 1 and 0, respectively. To help ourselves with solving the × 1. Before we can turn off the first (leftmost) switch, the switches The Knight’s Tour ... The puzzle can be solved in the minimum of 1’s: 111 2 switches and do this in the minimum number of moves if we want to have n Consider now the general instance of the puzzle represented by the bit string We will number the switches left to right from 1 to The tour given above is based on the idea proposed at the beginning of the It is also noteworthy that the − of general instance of the puzzle, let usFigure start 4.87). by solving its four smallest instances (see toggles. “off” states of a switch b in #140). The corresponding section[Sin10, of Section 5.F.1] D. runs Singmaster’s for eight annotated pagesthis bibliography and time, goes it back has to attracted the the 9ththe attention century. of greats Over several Leonhard noted Euler mathematicians, and including Carl Gauss. Since there are more than 10 knight’s tours on an 8 a chessboard (the other is the an optimal algorithm. In other words, we should first solve the same problem as should be in the state 110 n Solution Comments 16 central squares only as thesquare last as resort. soon In as addition, it we becomes willshown in always feasible Figure visit to 4.86, a do in corner which so. the Athey squares are tour are visited numbered generated by sequentially the by in knight. these the rules order is 128. Security Switches no computer help is not a trivial task. 18th century by Montmortis, and a De tour Moivre that for needflavor constructing not by an return giving to open a preference tour, starting togreedy that square. squares thinking The reachable is idea from used clearly fewer more hasby other a Warnsdorff: formally among greedy squares. by available This the alternatives, method proceedpossible choices suggested to for a a the square century next with later move. thetwo Warnsdorff’s greedy fewest methods, method but is it more is powerful morenote of computationally that demanding. the It both is these important methods to are just find a Hamilton circuit, and Warnsdorff’strying heuristic to is find one Hamilton that circuits. is regularly used for fail to lead to a solutionidea (in of our a case, heuristic-based by algorithm an is unluckyproblems. an break important For of one a other for tie). difficult algorithms In computational general,based for the on generating a knight’s version tours—several of thepp. of 175–186], divide-and-conquer which [Kra53, strategy—see, pp. for 257–266], [Gik76, example, pp. [Bal87, 51–67],devoted and to quite this a problem few and websites its extensions. Algorithmic Puzzles 206 loih.W aetefloigrcrec for recurrence following the have We algorithm. ie o h last the for given FIGURE o even For linear solution: second-order closed-form following the for obtain we 7.2]), technique Sec. [Ros07, or standard 476–478] pp. [Lev06, e.g., the (see, coefficients constant with by relations recurrence nonhomogeneous recurrence the Solving h rtsic ogt010 get to switch first the hr otels n o”cnb civdb eesn h pia euneof sequence optimal the reversing by last achieved the toggle be to can previously made “on” the which moves one from “on,” switches last it the the following all to Getting switches induction. third the mathematical all by with proved easily state be the can through pass to need will n n M h of oiin hswl ieu 011 us give will This position. “off” the − = n ( M M Let n =1 ntneo h rgnlpzl,wihcnb ovdrecursively. solved be can which puzzle, original the of instance 1 ) ( ( ntne ovddrcl,a hw nFgr .7 fe ht ecntoggle can we that, After 4.87. Figure in shown as directly, solved instances 2 =1 n n 0 1 = ) ) M 4.87 = = (2 n ( n s hsfruardcsto reduces formula this ’s, n M M etenme fmvs(wthtgls aeb h above the by made toggles) (switch moves of number the be ) pia ouin o h rtfu ntne fthe of instances four first the for solutions Optimal + ( ( 1 n n − − − n 1) n − M 1) 2) 0 0 1 =2 / wths hscnb oercrieywt the with recursively done be can This switches. 2 ( 3 =2 + + n . ) 0 1 1 2 1 ... = M + ( 2 3 .Nw eoew a ogetescn wthwe switch second the toggle can we before Now, 0. M n 2 − n ( n − 2) − 6 1 M + 2) ( 0 0 0 0 1 1 ... − ( n for 1 n + n 1) =3 ) .Inrn h rt0 ehv o the now have we 0, first the Ignoring 1. − M 0 0 1 1 1 1 =3 = n − ( wthsfo h o”psto to position “on” the from switches 2 (2 n n 0 1 1 0 0 1 M 2 1 − ≥ n + ( )or 1) 1 3 for n , ): − M n 2) (1) ≥ / euiySwitches Security 3 1 ; . = 0 0 o odd for 0 0 0 0 0 0 1 1 1 1 n , 0 0 1 1 1 0 0 1 1 1 1 =4 M =4 n (2) n s tyields it ’s, 1 0 0 0 0 0 0 1 1 1 1 = = puzzle. 1 1 0 0 1 and 1 0 1 1 1 0 0 2 . 207 Solutions k . The puzzle, . 3 transfer , 1 = 17 19 13 13 2 − = = = = > k (2) 1 1 c ’s book [Pet09, 1 1 − R n n Chinese Rings − − − − 2 , 1 4 3 2 1 solution. The value of Tower of Hanoi + 2 2 2 2 ) = + + + + k ( 9 1 3 5 R · · (1) · · 2 R , disks: 2 32 22 42 n (8). These values are shown in bold > R Tower of Hanoi n nk 512 3 and using this recurrence, we can find for = ,... , 7 9 5 9 1 11 ] 1 = = = = − (4) = (2) k − 1 1 1 1 R R 1 − k puzzle (see, e.g., the second tutorial), and, finally, , n − − − − − − 2 n 1 3 2 2 1 (3) 2 2 2 2 2 + 2 R 1 and ) + + + + + + k ) = 3 ( 1 3 1 5 k · · · · R ( · 2 R (1) 2 disks to the destination peg by the classic recursive algorithm for [ R n k Tower of Hanoi < 32 22 22 smallest disks to the destination peg recursively using all four pegs. The algorithm solving the puzzle is based on the decrease-and- made by this algorithm to move k can be selected to minimize the total number of disk moves made by − , k ≤ min ) Since the problem is an obvious extension of the 1 k n n nk 31 2 41 2 ( = R 1 or 2, solve the trivial instances of the problem in one and three moves, ) n = ( Starting with The puzzle was proposed by C. E. Greenes [Gre73]. It imitates operations n R smallest disks to an intermediate peg recursivelyremaining using all four pegs, then move the the algorithm. This leads tomoves, the following recurrence relation for the number of it is natural to use a similar recursive approach. Namely, if successively the values of If the three-peg transfer the respectively, as it is done in the three-peg parameter in the tables below. Solution Comments 129. Reve’s Puzzle abounding literature on the Chinese RingsSec. is 7.M.1]; annotated a by few D. recent Singmaster [Sin10, referencesp. 182]. can be found in M. Petkovi´ conquer strategy. Although solving theof second-order moves recurrence by for applying the theavoid number standard this by techniques following is either Ball both andand natural Coxeter Chein and [Bal87, [Ave00, pp. p. easy, 414]. 318–320], one In or our Averbach can view,the both above methods are solution. more cumbersome An than entirelymathematician different Louis approach A. was Gros proposedstates of in by the switches the 1872. by French bit His strings anticipatingsee method modern-day [Bal87, Gray pp. amounted codes; 320–322] for and to details [Pet09, 182–184]. representing of a very old and well-known called the Algorithmic Puzzles 208 Dd2,weeh aetesltosfor solutions the gave he where [Dud02], h rgnltrepgvrinafwyaserir ne h name the Under earlier. years invented few who a 1889, Puzzle version in three-peg Lucas original Édouard mathematician the French the by suggested u hscnetr a ee enpoe.Frsm te eeecs e David see references, other 7.M.2.a]. some Section [Sin10, For bibliography proved. annotated Singmaster’s been never has conjecture this but algorithm Frame-Stewart oqe.Hr h loih xlctysesteotmlsz euto neach on reduction size optimal the seeks iteration. explicitly algorithm the Here conquer. bv opttos npriua,frteegtds ntneo h uze n can one puzzle, the use of always instance eight-disk the for particular, In computations. above Comments n ihe ad[a0]smlfidi ute to further it simplified [Ran09] Rand Michael and p 26–29], pp. parameter partition optimal the the for of formulas value alternative produced have algorithm above the of analyses h loih’ xeso oa rirr ubro esi nw sthe as known is pegs of number arbitrary an to extension algorithm’s The h xeso fthe of extension The hs hr r eea ast rnfregtdssi 3mvsacrigt the to according moves 33 in disks eight transfer to ways several are there Thus, tapae nHnyE uee’ rtpzl book puzzle first Dudeney’s E. Henry in appeared it , 12 61 nk k = 42 22 52 32 h anagrtmcie eidteslto sdecrease-and- is solution the behind idea algorithmic main The n R k / ( = nec trto ftealgorithm. the of iteration each on 2 n 2 · · · · · ) R 13 n 5 3 9 1 =[ ( − k + + + + + ) ti rsmdt eotmlfraynme fpegs, of number any for optimal be to presumed is It . 1 812 nk n 2 2 2 2 + oe fHanoi of Tower 2 3 4 2 5 − − 1 2 − − − − k − n m 42 22 72 62 32 52 1 − = 1 1 1 1 − 1 k where k = = = = n − = o xml,acrigt e oh[Schw80, Roth Ted to according example, for : m − 2 17 · 33 21 · 21 · · ( 1 · 27 · · R 13 m 17 1 25 9 5 3 ( m + √ k + − + + + + + ) n 2 = 2 12 71 nk 2 1) 2 2 + n 2 2 2 7 uzet oeta he eswas pegs three than more to puzzle = 4 5 6 3 2 1 + / − 2 − − − √ 2 − − − 8 n 42 22 32 62 52 ] 0 − , 1 8 1 1 1 2 . 1 1 1 10 k n 5 m = = = =  = − = = − , + . 129 2 n 21 and 33 41 69 · · 1 33 · · 51 37 · · 7 R 1 13 17 5 9 3 1 , ( − k + + + + + + ) 1) h atruyPuzzles Canterbury The 2 2 2 2 + . 2 2 / 4 3 5 6 2 1 ae,mr detailed more Later, 2 2 − − − − − −  n , − 1 1 1 1 1 1 k = = = = − = = 25 25 37 65 1 35 29 h Reve’s The 209 Solutions 10)— ≤ i ≤ th slave (1 i eight slaves are enough to identify , 250 > 3. It is the only instance of the puzzle whose 8 12 3 456 BW B WBW [Sha02, pp. 16–22]. The puzzle has also been = n th bit from the right—dies from the poison, set the i (republished in [Gar06, Problem 9.23]) and Dennis WBBWBBBWW WBW (e.g., [Lev06, Section 4.3]), with the advantage of the . 517 WWWBB B Identifying a number by bits of its binary representation is a very = 9 Here is a solution for a. The poisoned barrel can be identified in 30 days as follows. Number 2 binary search Scientific American Doctor Ecco’s Cyberpuzzles + 2 2 + b. To achieve his goal with just eight slaves, the king can divide the barrels Different versions of the puzzle appeared in Martin Gardner’s November 1965 0 th bit of the poisoned barrel to 1; otherwise, set it to 0. For example, if only slaves the poisoned barrel in oneprocedure outlined group in in part 30 (a). days Sincethe king the by can poison apply the kills the algorithm same a algorithm analogous person toafter in the to 1 second, day, exactly the third, 2 30 and days, fourth days, and barrel 3 group the days, respectively. day Since there the is slaves just onebarrel die poisoned and barrel, will a uniquely particular identifynumber subset the in of group the group. dying containing slaves the will poisoned determine the poison barrel’s into four groups of 250 each. Since 2 i 1, 3, and 10 die from2 the poison in 30 days, the number of the poisoned barrel is who was “responsible” for the solution uses four spaces to the left of the line given; all the others use only two. Solution Comments 130. Poisoned Wine Solution 131. Tait’s Counter Puzzle actively discussed on interview puzzle sites on the Internet. old idea, going back atrelated least to 500 years (see [Sin10, Section 7.M.4]). It is closely the barrels from 0 to 999if and necessary, represent their these binary numbers expansions with by leading 10-bit999 zeros. strings, will For padding, example, be barrels represented 0 by and 0000000000first and slave 1111100111, drink respectively. Make from the second each slave of from each the of the barrels barrelsand that that so have have on, 1 until as 1 the their as second tenth from slave1 their the as is right rightmost their made bit, leftmost to bit, bit. drink Note the from that eachfrom each of all slave the the may barrels barrels have that a assigned “cocktail” have to madethe him, of because good the the wine barrels poison dilution does by notbarrel the can effect wine be from the determined by poison’s its bit potency. string In as follows: 30 if the days, the poisoned Shasha’s iterations performed in parallel. Part (b) takes the parallelism idea one step further. column in Algorithmic Puzzles 210 ie oteisac fsize of instance the to given eei ouinfor solution a is Here eei ouinfor solution a is Here eei ouinfor solution a is Here for solution a is Here trigwith Starting w biu atmoves: last obvious two WBBBBBBWW B B B B B WW WWWB B B B B B B B WBWWBBBWW B WWWWWWB W BBWW WWWB B B W W B WB BWBWBW WB BWBWBWBWB WB WWB BWW B WWWWBBB B B BWW B WWWWWW BWW WBBBWWB W BWW WB BWWWWBBB WB BWW BWBWB BW WB W BWBWWBB WB BWBW WB BWBWBWBWBWB WB WWBBBBBWW BWW BWBBWWWWWW W W BWWBB WB BW WB WBWB B W B B W BWBWBWBWBWBWBW 1011121314 9 8 7 6 5 4 3 2 1 BWBWBWBWBWBW 9101112 8 7 6 5 4 3 2 1 n WBBBBWW BBWW W WWWW W BW WB WBWB B B W ≥ BB W B WBWBW B W B 12345678910 8 , n n n ecngtaslto eusvl yrdcn h instance the reducing by recursively solution a get can we n = = = = 6: 5: 7: BB W B WBWBW B 12345678 4 . WBBBBB oeteWB__BWpten hc enables which pattern, _BBWW WBBW_ the Note n BBBBBB B B B WBBB − .Tefis w oe rnfr h ieto line the transform moves two first The 4. BBBB 211 Solutions . n 7 n ≤ 12 12 n − − n ≤ n moves. This 22 22 for 3 n − − n n n = 32 ) 32 n 8 alternating counters − BBWW ( − BBWW n n − M , n counters in 7 42 42 n − > − n n n 52 52 4 for 4. After its solution (with two trailing − − BWBWBW BWBBW W n + n ≥ 4 4) B BBBBBWW BBBBB − − ...... n n ( ...... : M n = ) n WB WB WB ( 8 alternating counters with two preceding empty spaces M − BWBW ...... n W The algorithm presented above is based on the decrease-(by 4)-and- a. To advance a peg three rows above the line, it is natural to target a 123 4 56 2 12345678 2 BWBWBWBW The above algorithm solves the instance with 2 b. Here, it is logical to take advantage of the solution given in part (a) by An extensive list of publications discussing this puzzle and its variations can be WBBW WBBWBWBWBW spaces) is obtained recursively, only twosolution more to moves the are instance of needed size to complete the followed by BBWW: WWWWW forms the puzzle’s instance of size Solution Comments WWW WB BW The sequence of 2 WBBW followed by two empty spaces followed by 2 132. The Solitaire Army conquer strategy. found in D. Singmaster’swas bibliography published [Sin10, in Section 1884 5.O].the by The general earliest P. case paper G. of Tait; themathematician. several puzzle authors to attributed Henri the Delannoy, solution a to French military officer and known configuration capable of advancing a pegconfiguration two is rows moved above one the row line up afteris (Figure this 4.88a). shown Such in a Figure configuration 4.88b. of Thethree 8 alternative rows pegs configuration above of the 8 line is pegs shown advancing in 1 Figure peg 4.88c. moving it one row above20 the pegs line below the and line then to reach looking it.Figure for An 4.89a execution an of shows initial this a plan configuration is configuration of showncapable obtained in Figure in of 4.89. part reaching (a) the (Figure cellthis 4.88b), which marked 8-peg is configuration with are an partitioned Xcells into marked three five with rows regions, the above same each itconfiguration number composed that The from of solves cells 1 the the of problem to via 5. a Figure transformation 4.89b to presents the configuration a in 20-peg assertion can be easily proved by strongthe induction number of or moves: by solving the recurrence for Algorithmic Puzzles 212 eorecuti ucinta sin uei au oec elo h board the of cell each to value numeric a assigns that function a is count resource A functions .22 etostoohr hw nFgr 4.90. Figure in shown others two mentions 212] p. n ed otk datg fseilfntoscalled this, functions prove special To of rows. advantage specified take the to reaching needs for one possible fewest the are statement thinking. divide-and-conquer the by helped is which strategy, conquer note4pgrgo ubrdwt ’ nFgr .9,ads on. transform so 4.89b and 4.89a, Figure Figure 1-peg in in 3’s 3’s respective with with numbered the numbered region into 4-peg pegs the transform 8 into pairs the 4.89b peg 4.89a, Figure The Figure in well. in as 2’s regions number and same the 1’s with with with marked regions, numbered region five same of the composed of is cells 4.89b the Figure in configuration The 4.89a. Figure FIGURE Comments FIGURE n c hwiiilcngrtoso est ec h agtconfiguration. target the reach to pegs 8 of configurations initial show (c) and 0pg orahtetre configuration. target the reach to pegs 20 h 0pgslto hw nFgr .9 sntuiu;Baly[Bea92, Beasley unique; not is 4.89b Figure in shown solution 20-peg The eddntakterae opoeta h e ubr ie ntepuzzle’s the in given numbers peg the that prove to reader the ask not did We 4.88 4.89 netdb .H owyadJ .Bada n16 Ba2 .71]. p. [Bea92, 1961 in Boardman M. J. and Conway H. J. by invented , (a) 1 a nemdaetre ofiuain( eoe h agtcl) at (b) Parts cell). target the denotes (X configuration target Intermediate (a) a nemdaetre ofiuaino es b nta ofiuainof configuration Initial (b) pegs. 8 of configuration target Intermediate (a) h ouingvnaoei rnial ae ntetransform-and- the on based principally is above given solution The 2 (a) 4 3 5 3 3 3 (b) 4 1 1 eorecounts resource 4 2 2 (b) 3 4 4 3 5 5 3 3 (c) 5 3 3 or 5 3 pagoda 3 213 Solutions 1 1 1 1 1 1 1 1 2 1 1 1 3 1 2 1 1 3 1 5 3 2 8 2 1 3 2 1 1 2 1 1 1 1 1 1 1 20, no seven or fewer pegs in any cells below the line can be 1 1 1 1 = 3 · 2 + Resource count proving that at least 8 pegs are necessary to reach a cell in Two alternative configurations of 20 pegs capable of reaching a cell in the 3 · 3 4.91 4.90 + 1 The most spectacular application of resource counts is arguably that by J. H. · Conway himself, who proved in 1961 that no amount of pegs can reach a cell at the transformed to a single peg at the target cell with the resource count of 21. the third row. fourth row above the line. FIGURE so that for any legitimate jumpoccupied of cells a after peg, the the jump sumoccupied is of cells not the before greater values the than assigned jump. the to Amongthe sum all infinitely one of the many given the resource by values counts J. for possible, proves D. all that Beasley the fewer than in 8 [Bea92, pegs p. cannotthe reach 212] a line. and designated (It cell shown is in here the assumed in thirdcells that row Figure below above all the 4.91 line the and values are not computed bycell shown adding for in two the values that immediately cells figure below above the are therow 1’s line. above for The the the line value that of is 21 designatedset is by assigned of the puzzle to seven as the or the cell target fewer in5 cell.) cells the Since for third below any the line, the resource count is not greater than FIGURE Algorithmic Puzzles 214 bikr) n pcsi te“ldr)aesoni iue4.92. Figure in shown are “glider”) (the spaceship and “blinker”), h uzesalgorithm. puzzle’s the Solution powers used Conway fact, counterintuitive this ( prove of To line. the above row fifth Comments FIGURE 3.TeGm fLife of Game The 133. 197–198]. pp. [Tan01, the numbers Fibonacci that (Note websites. names Desert. several the the under on known as also games well is mathematical as on puzzle book Conway classic by the in coauthored found [Ber04] be can proof remarkable this of bikr”()Te“ldr ecnigdaoal n eldw n otergti four in right the to and down cell one diagonally generations. descending “glider” The (c) “blinker.” √ 5 − 4.92 1) .Tno rvdtesm atb sn eorecutbsdo the on based count resource a using by fact same the proved Tanton J. ) h mletsillfs(h bok n h tb) siltr(the oscillator “tub”), the and “block” (the lifes still smallest The The / 2 h uzeak odtrieipt opoueseie upt by outputs specified produce to inputs determine to asks puzzle The , h eirclo h so-called the of reciprocal the aeo Life of Game (a) ofiuain:()Te“lc”adte“u. b The (b) “tub.” the and “block” The (a) configurations: (c) owysSoldiers Conway’s odnratio golden ( √ and (b) 5 + edn cusinto Scouts Sending 1) / 2 . h details The 215 Solutions l m itself, is odd m m and and l m If the number of . P is odd and the same should be colored to can be colored either m would have been even P l itself, we would have to P l was selected, this would and l l 1, proceed as follows. Select as required by the problem’s and l P > n is even, exactly one half of its points m and l can always be colored to satisfy the problem’s P ). Because of the way line P columns [Gar83, Chapters 20–22]. It still commands a while the other color—white—occurs more often on l was invented by the British mathematician John Conway be the other grid line passing through point m The problem, which was offered to participants of the XXVII should be colored to even out the color occurrences on that other line. Recursively, color all the points except The problem can be solved by the following recursive algorithm. If . P l , the Soviet Union magazine in physics and mathematics for school Game of Life (horizontal or vertical) that contains an odd number of the given points; having exactly one half of its points colored black and the other half colored Scientific American l 1, color the point either color, say, black. If m Kvant Finally, we need to show that the situation in which one color—say, black— The on line = colored black and the other half colored white; therefore, color. If the number of the coloredthe points other, is even on one of these lines and odd on 134. Point Coloring significant interest, as can be seen from agame number is of interesting the in websites devoted several to ways. it. First,and The Conway’s simple quite rules unexpected lead to patterns. fascinating universal Second, computer the [Ber04, Chapter game 25], which can leadsmechanics be of to evolution profound used to questions the as from nature of a the model Universe. of a statement. We will showrequirement. that Let is impossible if the number of colored points on each of the lines occurs more often on even out the color occurrences on each of these lines. color occurs one more time than the other on both lines, If the number of the colored points on each of the lines the colored points on each of the lines a line if there is no such line,P select any line with at least one point on it. Select a point in 1970. It became widelyin his popular after Martin Gardner wrote about the game imply that every line containsand an even number of points,white. with But each if line we except thenadding compute the the colored points total on number all of the lines points parallel colored to each color by Indeed, in such a situation, the number of all the points on Comments Solution students and teachers (Problem M1019, p. 26). The solution by A. P. Savin, International Mathematical Olympiad, appearedof in the December 1986 issue n conclude that the total number of black points iswhite one points; more if, than on the the total number other of hand,each we compute color the by total adding number of the points coloredwe colored points would have on to all conclude the that lines thethe parallel total total number to of number white of points is blackalgorithm’s one points. correctness. more than This contradiction completes the proof of the (odd colored points plus Algorithmic Puzzles 216 n iieiscrufrneb 2 by circumference its divide and hc ilsanwmt o h etrpitadanwpiigo h te points other the of pairing chords. new new a the and of set point the center by the for mate new a yields which fti al.T eeaetenx 2 next the generate To table. this of FIGURE Solution Pairings Different 135. our In 26–27). (pp. issue decrease-and-conquer strategy. 1987 the of variety April decrease-by-one the on the based is in it terminology, published was above, reproduced FIGURE from2to2 lutae hsfor this illustrates n n ftepit ntecrufrne hc ilsoepi,adteother the and pair, one yields which circumference, the n on points the of one and h nre xet1i h atgnrtdtbe iue49 hw nexample an shows 4.93 Figure table. generated last the in for 1 except entries the fcety o ovnec,nme h hlrnfo o2 to 2 1 a from in children numbers the number convenience, For efficiently. − 1 6 h te a odsrb h loih st akwt h etro circle a of center the 1 with mark to is algorithm the describe to way other The n ar r bandb h hrspredclrt hsdaee.Fgr 4.94 Figure diameter. this to perpendicular chords the by obtained are pairs 1 = 2 5 4.93 4.94 3 . 3 4 n eei n ftewy ognrt 2 generate to ways the of one is Here iest ftredfeetpairs. different three of sets Five emti a ognrt arnsfor pairings generate to way Geometric . e fpisi bandb rwn h imtrtruhtecenter the through diameter the drawing by obtained is pairs of set A × n 5 1 n 2 = al.Tepisfrtefis e r ie ytecolumns the by given are set first the for pairs The table. .Nwst fpisaeotie yrttn h diameter, the rotating by obtained are pairs of sets New 3. 6 4 3 2 n 3 6 4 1 − qiitn onsnmee clockwise numbered points equidistant 1 5 3 n 1 − 2 6 es oaesy clockwise—all rotate—say, sets, 2 n = n 3 1 3. − 2 4 eso ifrn pairs different of sets 1 5 4 6 5 n n lc these place and 2 1 6 3 5 4 217 Solutions no no and , , a 0 0 a = = t t units each time 0) at , b 1 − 2,22,2 2,12,1 2,02,0 2,2, computed by this formula for 0 and moves 1 − = 1,01,0 ,... 1,11,1 puzzle. t 1 1,1, ) in a sequence and checks the spy’s , 0) (Figure 4.95). This will lead to the b at 0 , , [Kra53, pp. 226–227]. Of course, the a a = can be computed by the obvious formula t t 0,00,0 b Catching a Spy is; hence, after checking the pair (0 b ) in the sequence. Then whatever the parameters b he can be discovered by probing this location at , , 1 a ) can be enumerated in many different ways. In particular, one 0 − b 1,11,1 , = . Therefore, the problem can be solved by any algorithm that 1,01,0 − a 1,1, t − ) needs to be checked. bt − The algorithm can be thought of as based on the representation b Mathematical Recreations , Since the spy is at location + Spiral solution of the a 4.95 = participants. ) n t ( Integer pairs ( Both interpretations of the algorithm outlined above were given by Maurice defining the spy’s movement, the algorithm will reach this combination after a ab location at consecutive time intervals other pair (0 the corresponding ( interval, the spy’s location at time enumerates the set of all integer pairs ( can think of the pairs as integerby points moving of along the Cartesian a plane spiral and originating enumerate them at (0 b finite number of steps to computeat the location spy’s 0 exact at location. Obviously, if the spy is matter what the value of x FIGURE Solution Comments 136. Catching a Spy change strategy. Kraitchik in problem is another wordingwith of game scheduling in a round-robin tournament Algorithmic Puzzles 218 ± e hoy hsmto osdr h ( the considers method This theory. set ob ipe hnteatos ouinbsdo h ignleueaino the of enumeration diagonal the on matrix. based infinite solution seems authors’ It the reviewers. than book’s simpler the be of to one University, Madison James of Lucas Stephen it h lmnso h arxi re fisnrhatt otws diagonals southwest to northeast its of order in figure. that matrix in shown the of elements the lists rbn h p’ oain at locations spy’s the probing Comments FIGURE x X 00 2 h euneo h oain rbdb h loih ilsata follows: as start will algorithm the by probed locations the of sequence The mathematical of method enumeration standard a follow can one Alternatively, hs osadclmscrepn odfeetvle of values different to correspond columns and rows whose ,... r akdb natrs eas hyaentue ytealgorithm. the by used not are they because asterisk an by marked are a a a a a 4.96 and ) 0 = = = = = 0 + + 1 − 1 0 − 2 arxslto fthe of solution Matrix − 1 2 0 + 0 h rtslto ie bv a ugse oteatosby authors the to suggested was above given solution first The b · 1 · ( 0 − − ( 0 − + b b 2,0 1,0 2,0 1,0 0 = = 1) 0 = ,0 = 0 · 0 · , 0 0 4 , 4 1 , 1 =− =− + ± − + − 1 2,1 2,1 0 1,1 b 1,1 , 0 1 · 3 * ± = , · 1 , − 1 2 − 1 acigaSpy a Catching = ,... 1 = 1 − 1 − + − 1 , 2, 2, , b 1 ,rsetvl Fgr .6.Temethod The 4.96). (Figure respectively ), 1 1, 1, 1 a 1 , * + · = · − b − 5 + 5 − − − ar seeet fa nnt matrix infinite an of elements as pairs ) 1 1 1 =− 1 1 = 1 1 · 2 · uze h lmnsi o except 0 row in elements The puzzle. 4 2 − − = , 6 b 2,2 2,2 2 1,2 1,2 = , * 3 1 = + , 3 − 2 − , 0 − 1 1 · 1 6 + · − − 6 + = b 2, 2, 1, 1, 0 =− * = 1 · 2 − 3 − − . · − − 2 3 2 2 2 =− a 2 5 = ,... ( a 2 1 = , , 0 , ± 1 , 219 Solutions , 1 4 2: 2 0) 2) / / / n − n n + coins > 2 4 / n k / n , n k ,... , 4 1 = + To arrive at the n 4 . / First, perform the 2 8 are illustrated in n / move the top coin of . 2 coins. Then move , n , n / 4 = n / coins ( 2) n n / n n = coins to the right to land i i is a multiple of 4. n 1: for the rightmost single coin, find is even, the last move, numbered i − 4 / 4 and move it to the left over all n 1 coins respectively. The top coins should be / n must be a multiple of 4. single coins in a row, take the top coin of the n ,... , n ,... , 2 if and only if 1 , , 1 2 2) coins are already paired, and hence one of the two − / coins between them and place that coin on the rightmost n 4 = − i / i 1 and move it to the left over all n ≤ n i + ≤ 4 / 1 n , i The solution to the puzzle provides an excellent example of the must be a multiple of 4. To prove this, consider the state of the puzzle The puzzle has a solution if and only if n “Reversing” the above, we obtain the following algorithm for pairing One can devise an algorithm for solving the problem by backward thinking as Obviously, the problem cannot be solved for an odd number of coins, because The above solutions are, in our terminology,The representation change authors examples. came across this puzzle perusing the Internet puzzle collection by This algorithm obviously makes the minimum number of moves possible The puzzle and its solution was attributed by Martin Gardner to W. Lloyd pair numbered on a single coin. The operations of the algorithm for placed in a row and numbered left to right from 1 to initial state of the puzzle with the top coin of the pair numbered coins. Then, starting with the leftmost remaining pair (initially numbered are paired, with the pairs numbered left to right from 1 to take the leftmost single coin and jump it over coins. Continue this process of moving theto the top left coins of of them until the the pairs top over coin of all the the leftmost coins pair is moved to the left over placed as single coins as justspacing between described—recall adjacent that coins. we are supposed to disregard follows. Consider the puzzle in its final state in which and ending with the rightmost pair (initially numbered in the final state all the coinsMoreover, are arranged in pairs, making their totalbefore number even. the last move: ( 137. Jumping into Pairs II K. R. M. Leino of Microsoft Research [Leino].its They origin, have which not is be not able totally to surprising determine given its subject matter. because it forms a new pair of coins on each move. Figure 4.97. the pair to the left over following operation for the coin to its left to have Comments must be even, which implies that Solution remaining single coins should make aon jump the over other an single even coin. number Since ofcoins a on coins coin move to is land required to jump over an even number of occasional usefulness of backward thinking in algorithm design. Milligan (see [Gar83, pp. 172, 180]). single coin. Then repeat the following operation for Algorithmic Puzzles 220 rhrniho otergthv eoeawitebo.Atrtewiteblow, whistle the After blow. whistle a before had have who child right the the to neighbor her or nta itiuin(ealta ti vn,then even), is it that (recall distribution initial after Solution Sharing Candy 138. FIGURE hsfruaipista if that implies formula This cutn onecokie aigmr than more having counterclockwise) (counting bv,tepoeswl euti ahcidhvn h aenme fcnypieces candy iterations. of of number number same finite the a having from after child limited each also in is result have will can process child the a above, pieces candy of number the Since increase. will have hl ilhv tleast at have will child formula: icsaycidcnhv ee exceeds never have can child any pieces hw ngray. in shown otergtbt had both right the to fcnypee hl a eoeapriua hsl lw fe htwhistle that After blow. whistle least at particular have a will before child has every child blow, a pieces candy of ee1 were m k trtos h iiu ubro icso ade mn hs children these among candies of pieces of number minimum the iterations, icsatrtewitebo u the but blow whistle the after pieces 4.97 ≤ k Let ouint the to Solution < i n i  and = hlrni o with row a in children i ⎩ ⎨ ⎧ icswl have will pieces j e epciey h ubro ad icsacidadhis and child a pieces candy of number the respectively, be, m i i / / m 2 2 icsbfr h hsl lw oegnrly fthere if generally, More blow. whistle the before pieces upn noPisII Pairs into Jumping i + + + = j j icsuls h hl n i rhrneighbor her or his and child the unless pieces 1 / / M fti ubri even is number this if 2 2 , + where otherwise 1 m i  / ics where pieces, 2 m M + M ad icswiete( the while pieces candy k slretnme fcnypee nthe in pieces candy of number largest is m hcidwl aemr than more have will child th e now Let . uzefor puzzle i /  2 m ≤ = . h first the , M m i .  n hs h ubro candy of number the Thus, sdfie ytefollowing the by defined is m ad ics oevr a moreover, pieces; candy = etesals number smallest the be .Tejmigcisare coins jumping The 8. k − , fte ilstill will them of 1 k + )hchild 1)th m Hence, . 221 Solutions we can puzzle. , clockwise 3 (If it were . C > B n and : Any graph with B would have been at B (b)(b) C be two enemies seating B B Then there exists among the is friendly with and . King Arthur’s Round Table D Dirac’s theorem A A each of the three knights is friends , 3 D 2 friends, the number of his enemies / = n n If . (Figure 4.98) 1 A − 2 / n in 1989. (We have omitted the assumption that the = themselves (shown by the arrows in Figure 4.98a), we 2 C / n Kvant whose neighbor to the left to the left of − and C B 1 B (a)(a) − B n The puzzle and its solution are from the paper on monovariants The problem exploits the idea of a monovariant, which is the knight Iterative improvement of a seating in the C Since each knight has at least A 2.) If we now swap the seats of all the knights between 4.98 / n A The problem is rather well-known; in particular, it was given in the 1962 D including knights will get a seating(Figure arrangement 4.98b). with at least one fewer pair of enemy neighbors with the two others and hence they can be seated in any order. In start with an arbitrary seating of theseating knights next and to count each the other. number of Ifdecreased enemy this at pairs count least is by zero, one we as are follows. done; Let if knights it is not, it can be friends of not true, the number ofleast the knights who are enemies with cannot exceed next to each other, Comments FIGURE Solution Comments [Kur89] published in number of knights isexistence even, of a which solution is to the unnecessary.) puzzle It follows from should be noted that the 139. King Arthur’s Round Table minimum number of pieces innotion a of candy a distribution monovariant before istechniques.) a discussed whistle in blow. the (The book’s tutorial on algorithm design Beiging Olympiad and 1983 Leningrad All-City Mathematical Olympiad. For some variations of the problem, see a paper by G. Iba and J. Tanton [Iba03]. Algorithmic Puzzles 222 Solution n FIGURE 4.The 140. friendly. vertices are two vertices the between by edge represented an knights is the there if and only knights and if the are graph the of vertices the n 4.100b). (Figure board larger the of column last the of uesi os2 rows in queens once oi ya de sa least at is edge) an by it to connected h uesi columns in queens the ue ntemi ignl h ouincnb xeddt il ouinfor solution example). an a for yield 4.99c to Figure extended be of can value solution next the the diagonal, main the on queen lc ueso uhbad si a oeaoeadte erag hm tis it them, rearrange first then the of and rows above odd-numbered in done queens was with start it to as easier boards such on queens place any ic h ouinotie nti a a oqeno h andaoa,i can it diagonal, main the on for queen solution no a to has expanded way be this in obtained solution the Since 1 yecagn h oso h uesi oun and 1 columns in queens position the nonattacking a of get rows to the possible exchanging is by it Then rows. even-number in queens by tutr fsltosfrohreven other for solutions of structure rm2to 2 from nlsv,adte wptefis n eutmt ubr.Apn otels the list the to Append numbers. penultimate and first the swap then and inclusive, inclusive. , > ≥ Q 3 notntl,ti osntwr for work not does this Unfortunately, hs ehv h olwn loih htgnrtsrwnmesfrplacing for numbers row generates that algorithm following the have we Thus, ae1( 1 Case remainder the Compute ae2( 2 Case .., ,... n uesi osctv oun fan of columns consecutive in queens 3 etcsi hc h ereo ahvre ie,tenme fvertices of number the (i.e., vertex each of degree the which in vertices 3 = Q (a) 4.99 6 n k n Q n nlsv,adapn oi h osctv d ubr rm1to 1 from numbers odd consecutive the it to append and inclusive, , h ouinfor solution The r r ouin othe to Solutions Qen rbe Revisited Problem -Queens eg,Fgr .9) oevr ic oeo hs ouin lcsa places solutions these of none since Moreover, 4.99b). Figure (e.g., − snihr2nr3:Wieals ftecneuieee numbers even consecutive the of list a Write 3): nor 2 neither is s2:Wieals ftecneuieodnmesfo to 1 from numbers odd consecutive the of list a Write 2): is Q .Ide,ti ok o nyfrany for only not works this Indeed, 1. , n 4 yjs digaqeni h atrwo h atclm (see column last the of row last the in queen a adding just by .., ,... n Q / 2 n + -uesProblem n-Queens r / Q ;frtelast the for 2; fdivision of n n and 2 = = Q (b) hw nFgr .9 ugsstefollowing the suggests 4.99a Figure in shown 4 9 n + Q sea xml for example an (see n 6 n / k n s o h first the For ’s. Q a aitncrut o hspuzzle, this For circuit. Hamilton a has 2 ypaigteetaqena h atrow last the at queen extra the placing by y6. by n n n o (a) for / = Q × oun,paeteqen nrows in queens the place columns, 2 8 n + board. n 6 = Q k . ,(b) 4, lhuhi spsil to possible is it Although n Q n n n / = / = 2 n oun,paethe place columns, 2 Q n / 4 − nFgr 4.100a). Figure in 8 oun followed columns 2 = + (c) n h osof rows the and 1 Q ,ad(c) and 6, 6 k Q u lofor also but Q n = Q 7. n n , , 223 Solutions n Q Q 9. Q and append = n n Q Q , the first pass through ’s we have to start with (b)(b) k n 2 8 and (b) Q 1 instead of = ’s we have to swap two pairs = n − n n Q n Q for (a) Q , inclusive, and then swap number 4 and the n is even, that is, is odd are obtained, in fact, as extensions of the n n Q Queens Problem 1) boards. - Q n − is one of the most well-known problems in recreational n Q ( × Q boards where ) be the survivor’s number. It is convenient to consider the cases 1) ’s separately. If n n n (a)(a) ( − Q J × The above algorithm, which follows an outline by D. Ginat [Gin06], n Solutions to the n is 3) Apply the directives of Case 2 to Q Let r Queens Problem - 4.100 n Q Q The Case 3 ( 141. The Josephus Problem mathematics and has attracted theof attention of the mathematicians 19th since the century.much middle The later, of search course. forbacktracking—as Among we efficient a do algorithms in variety this for ofto book’s solving approaches, first introduce tutorial—has solving it this become the started a general problemeducational standard technique merits, way by backtracking in has the algorithm advantage textbooks. ofall finding, the In at least solutions addition in to principle, tomethods the the can problem. be If employed. just Thecontains one more survey than solution half paper a is by dozen sets the J.positions, of including goal, formulas Bell the for earliest much and one direct by computation simpler B. E. of Pauls queens’ published Stevensalternative in 1874. had [Bel09] Surprisingly, been this all but ignoredalerted by the community computer of scientists its until existence B. [Ber91]. Bernhardsson of even and odd to the created list. solutions for ( Solution Comments consecutive even numbers from 2 to FIGURE last number in the expanded list. is rather straightforward in that it placescolumn queens of in the the first board. available The square nontrivial of part each is that for some the second square in the firstof column, queens and to for satisfy some the nonattackingsolutions requirement. for It is also worth noting that the Algorithmic Puzzles 224 eurne fteJspu rbe o n ongtv integer nonnegative any for problem Josephus the of recurrences i 1 odd an of case the consider now us Let survivor, in need the for simply be particular, we will In person, one. obtain 5 subtract a we and position of two position initial by initial position in new the his 3 person get multiply to a to position Thus, pass, initial on. second so in and the 3, person for position a 2 only position example, The in size. for initial be numbering; its will half position but in problem same is the difference of instance an yields circle the If 0 lmntspol nalee oiin.I eadt hsteeiiaino the size of of instance elimination an the with left this are to we that, add after we right 1 If position positions. in person even all in people eliminates nisetn hs aus ti o ifiutt bev htfrthe for that observe 2 to for is, difficult that 2, not of is powers consecutive it between values, these inspecting On eto .] sn h nta condition initial the Using 1.3]. Section odto.Asmn htfragvnnneaieinteger nonnegative given a for that Assuming condition. nuto’ supin eobtain we assumption, induction’s o vnadodvle of values odd and even for value ubr rm1t 2 to 1 from numbers utpytenwpsto ubrb n d .Tu,frodvle of values odd for Thus, 1. add and 2 to by have number we position numbering, new position the new multiply the to corresponds that position initial the get , , = J i 2 1 ti o ifiutt rv yidcinon induction by prove to difficult not is It for formula explicit an find To ( n see,i a erpeetda 2 as represented be can it even, is .., ,... .., ,... n 0 ) , p 1 = .., ,... J 1151 111315 9 7 5 113135713 123456789101112131415 (2 2 15: ,w have we 0, p p + − 1 2 J 1 (2 p + , J − p J (2 i + (2 ) p 1 1 p + = = p , J + + 1 + (2 h orsodn ausof values corresponding the 2(2 J − (2 i i 0 ) ) i ) 1 p + = = j . J + = + n (2 hsosraincnb xrse yteformula the by expressed be can observation This 1 eoti h olwn ausof values following the obtain we , 0) J 2 2 2 (2 k 1) + i i i + + J + = k + ( 2 − ) n j for 1 for 1 1) ) ) 2 1 = 1 , , = · j ewl olwtepa ulndi [Gra94, in outlined plan the follow will we = ene oso that show to need we = 2 0 n where J J i i + (2(2 > 2 ( 2 = = J k J i (1) ( ) 1 + ,ta is, that 1, k 0 0 p − ) p = p , , j 1 ≤ 1 1 + + = = . 1 htti oml osslethe solve does formula this that .., ,... , ,... ,a tsol efrteinitial the for be should it as 1, . n 1 j n h bv recurrences above the and 1 0 )) . < ≤ J = n ( 2 n 2 2 j p = u h ag fodd of range the run ) 2 p p + < + J − 1 2 (2 1 p or k 2 − 1 p p + n o every for and . . n + 1 . .Tefis pass first The 1. = hnuigthe using Then p j ) . J 2 o h basis the For − ( p n k for ) 1 + n . n svalues ’s ee to Here, ,weget i where n i = = 225 Solutions , 2 = 1 means (40) + J − 101000 ) j or = + + means that the p Then using the 40 ) by the formula (2 > J n ). . ( 2 p = against the Romans. J − 2 person is eliminated, = n < C.E. 1) j , +  second ≤ n ) 2 j log ) or lighter ( + p + + 1 . 2 1 (2(2 1 where 0 − J + n i + = 2 2 j + 1) = ) by a 1-bit cyclic shift left of the binary means that the left pan’s weight is smaller than 1 n 1 + ( J j < = + Alternatively, one can also find 2 ) . 17. n + 1) ( 17 J 1 means that the weights are equal, and = + +  = j p = [Gra94, p. 12]. For example, if 40 2 (2 2 2(2 J n log = = + 10001 ) ) or each coin is either heavier ( 1 i This puzzle is named for Flavius Josephus, a Jewish historian who 2 = = + The decision tree in Figure 4.101 presents an algorithm that solves − ) 1 2 + p 40 · (2 2 J is odd, it can be expressed as 2 means that all the coins are genuine, and a number followed by The puzzle discusses the version in which every Finally, one can also get i + (101000 that the coin with thatinternal number node is indicates heavier or the lighter, outcomesindicated inside respectively. that the A node. are For list example, still before above the possibleare an first genuine weighing before ( either all the the coins weighing representation of induction’s assumption, we obtain 142. Twelve Coins which makes it easier toDavid solve. Singmaster’s For annotated bibliography other [Sin10, Section variations 7.B] and and,other among historical less many exhaustive references, sources, see the book by Ball and Coxeter [Bal87, pp. 32–36]. Josephus, as a general, managedafter to the fall hold of the the city fortress he of tookrebels refuge Jotapata voted with for 40 to diehards 47 perish in days, a rather nearbyand, but than cave. proceeding There, surrender. the around Josephus it, proposed kill towas every form supposed third to a kill man circle himself. until Josephusperson just contrived and to one be when man in just was a he left, positionintended and to who victim another be to man surrender that to remained last the alive, Romans. he prevailed upon his that of the right’s pan, left pan’s weight is larger than that of the right pan. Leaves indicate final outcomes: = Solution Comments mentioned in [Weiss]. Using the same value1 of 40 for an example, we get J If participated in and chronicled the Jewish revolt of 66–70 the fake-coin puzzle fornumbered 12 from coins 1 in to 12. threeweighted Internal weighings. listed nodes In indicate inside this weighings, the with treeweighing node. the in the For coins which coins coins example, being 1, are the 2,pan root 3, of 4 corresponds the and scale, to coins respectively. 5, the Edgesthe 6, to first node’s 7, a 8 weighing node’s are outcome: children put are on marked the according left to and right Algorithmic Puzzles 226 soitdwt n loih ovn h rbe ilhv ohv tleast at have to have will problem the solving 2 algorithm any with associated nte“egig1 on,a d al( eeto fTetet)pzl”page puzzle” Treatments) of Selection (A [Bogom]. references Ball from Odd the an see coins, system, 12 ternary For “Weighing the 22–25]). the on on pp. based [OBe65, one (e.g., the weighing including what second solutions, on other or depend not first does the round third either the on in weigh happened the to of what outcome of the choice on a depend and not one, does first weighing to second what In the of for coins. choice balance a of the is, on pairs that put solution, same nonadaptive completely the a involves has problem weighings the of fact, round subsequent either scale the the tips and weighing first way, the if coins same the involve weighings second the ol a.T .OBin rtsi i okta thsbe lee that alleged been has it Second that the book during his or in eve writes the O’Beirne on either H. arisen T. have War. to World seems It 5.C]. Section in findings 1946. their in published who mathematicians several by FIGURE Comments ilhv ostsyteinequality the satisfy to have will weighings of number the to equal on requires coins 1 < · - h rbe antb ovdi ee hntrewihns eiintree decision A weighings. three than fewer in solved be cannot problem The notmlagrtmfrtegnrlisac fti rbe with problem this of instance general the for algorithm optimal An h rtpbihdacut fti aospzl perdi 95[Sin10, 1945 in appeared puzzle famous this of accounts published first The 12 9 1 < 1 5 - - < : + + 5 1 9 4.101 + 0 9 1-2-3-4-5+6+7+8+ = 1 - 1 , = 6 2 < 5 , - eiinte o the for tree Decision 5lae eetn l h osbeotoe.Teeoeisheight, its Therefore outcomes. possible the all reflecting leaves 25 , h trcieeso h ouingvnaoele nissymmetry: its in lies above given solution the of attractiveness The 7  9 9 , <> log 1 2 < 3 2 , : 8 1+ - : - 1 1 = 3 -11+ 4 = 0 0 3 - , (2 4 : 4 = 1 - - 1 n > = + 8 1 1 < + – + 0 3) 2 - > 7 6 6  + – + : + = < 8 egig.Ti atwsetbihdindependently established was fact This weighings. 3 7 1 6 + wleCoins Twelve – + W 2 1 8 + W - 91 112 11 10 =9 101112 , 4 + > > 2 – + ≥ – + 9 , efre yteagrtmi h os case, worst the in algorithm the by performed 5 , 3 1 1 , + – + – 2 log = 0 4 = 6 : +12- : = : 1 + – 1 1 3 5 = 1 + 2 – 7 , 25 , puzzle. = – + 6 6 < 1 , -  8 + – 7 1 6 – + or , 6 2 - 7 > 8 9 : 7 + - W = 8 1 - + – < 0 8 8 1 + - 1+2+3+4+5-6-7-8- ≥ - 0 > – + 1 3 4 < 1 . + ahmtclGazette Mathematical + – < 1 1 2 3 9 2 2 1 + + : : - – + 3 = 4 1 9 +4+ 5 1 +11- 0 + , , 2 1 9 6 + 0 , , > 1 7 = 0 , 9 , 8 + 1 > : = 1 5 1 1 n : - + = 9 5 ≥ - 1 + 3 > > > 227 Solutions n 1 > n squares that 1 for n [Win04, p. 79]. board. + n 2 / × 2 n n  infected squares that will infect the Mathematical Puzzles n as the virus spreads. Hence, the entire board n squares is the minimum number needed, note that the . n n will never be entirely infected. n The puzzle exploits the idea of monovariant mentioned in the Two initial configurations of infected squares that will spread to the entire infected squares capable of infecting the entire board; Figure 4.102 shows two of them. The following recursive algorithm solves the puzzle by removing The answer is n n × 4.102 n The puzzle was included in Peter Winkler’s In order to prove that There are many initial configurations of with the perimeter of 4 board. are initially infected, the total perimeterinitially, of and the it infected will remain region less will than be 4 less than 4 total perimeter of the infected region (which,perimeters in of general, contiguous is subregions equal to infected the bythe sum the virus of virus) the spreads cannot over increase the while two board. of Indeed, its when boundary a edges are newboundary absorbed square edges into is are the infected, infected added at region, to least and it. at most Therefore, two if there are less than 144. Killing Squares Béla Bollobás [Bol07, p. 171] considered the versionthree of infected the neighbors puzzle are in needed which to at infect least a new square. Solution Comments FIGURE Solution 143. Infected Chessboard this puzzle “diverted soconsideration much of war-time a scientific proposalenemy effort to territory” that inflict [OBe65, there p. compensating was 20].most damage popular serious Since puzzles by ever, then both dropping the in puzzle puzzle it books and has in on become the Internet one puzzle sites. of the discussion of iterative improvement in the firstimpossibility tutorial, of but a it certain is used kind here of to afewer prove than solution—namely, of an initial configuration of the minimum number of toothpicks, which is equal to entire Algorithmic Puzzles 228 lutae nFgr 4.104. Figure in illustrated stkncr fb eoigasnl otpc.Ti bevto a eeasily be can observation This toothpick. single induction. a mathematical using removing by by formalized of perimeter its care and board, taken the inside is lines straight the break frames adjacent the tiling eieeso h qaegvnadtesur fsize of square the and given square the of perimeters FIGURE when 1 to equal is course, of (and, FIGURE nFgr 4.103. Figure in eusvl h uzefrtesur fsize of solve square Then the given. for square the puzzle of the side upper recursively the remove in domino, last toothpick that horizontal For ring. second the frame the in the domino every tiling last the ring remove of domino toothpick counterclockwise, the the of for going line except middle and the frame been have the would of that toothpick corner left top the with h frame. the nanthl,teagrtmwrsbcuetemdl ie ftedominoes the of lines middle the because works algorithm the nutshell, a In If h loih’ plcto othe to application algorithm’s The X X X n 4.103 4.104 > X X X 3 , The The X otefloig osdrtefaeo it omdb the by formed 1 width of frame the Consider following. the do X X X iln Squares Killing Squares Killing (a) X X X X X X X X ouin o (a) for solutions for solutions n X X X X = X n 1) × . n If n orsfree n d ausof values odd and even for boards n X X X = n = n X 1 − = , 1 n X X X , nietesalrbre of border smaller the inside 2 X n (b) and 6 2 = X , r3 h ouin r given are solutions the 3, or X 2 X X , n and X X X X − (b) n X X n X niei.Starting it. inside 2 = = X X X X 7. 3. X X X X X X X X X n is 229 Solutions 1 = > 2 n + )asthe column, If 2 . / 1 and 3 may is equal to 2 dominoes is even. If we ,... , 1) / + n 2 n 2 the number of 10 − n 2 , , , / 1 ) 2 2 6 n n n ( 1 square. Thus, the , = 3 K × n , Scientific American 2 square, which contributes is equal to ( × 1 is the minimum number of is even, there are n n 3 square, which contributes two. In 2 dominoes in the tiling of the frames; + × / 2 / 1) 2 2 toothpicks need to be removed. These n / − 2 2 n n = Colossal Book of Short Puzzles and Problems ) n ( 2 light cells. To eliminate unit squares formed by the K / 2 n 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 15, 141, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15 (1) (2) 1 is odd, there are ( > The algorithm solving the problem is clearly based on the decrease- n Reading the tile numbers top down and left to right, we can associate . If 2 dark cells and 1 / . 2 1 n + + 2 2 toothpicks can also eliminate all the unit squares formed by the perimeters of 2 / The puzzle had been found by Martin Gardner in a collection of puzzles by It is easy to show that The domino tiling also immediately yields the formula for 2 / / 2 2 n 145. The Fifteen Puzzle which was later[Gar06, included Problem 1.20]. in his total number of removed toothpicks for an odd in the tiling; eachfor of this one dominoes of contributes the one dominoes removed covering toothpick, the except central 2 n Sam Loyd. Gardner used it in his November 1965 correct answer to the puzzle. two. Thus, the total number of removed toothpick for an even toothpicks removed by the algorithm. Indeed, if toothpicks that need to be removed to eliminate all the squares when each of these dominoes contributes onehorizontal removed dominoes toothpick covering except the central for 3 one of the perimeters of the dark cells, at least lead one to the wrong expectation of triangular numbers (1  n is odd, a somewhat more sophisticated argumentthat (see the [Gar06, same pp. formula, 31–32]) rounded shows upnumber to of the toothpicks nearest that need integer, to still be gives removed. the minimum the light squares as well, but onlylight if square. each Since removed there toothpick is separates no a such darkmore toothpick and toothpick on a needs the board’s to perimeter, be at removed least for one the total minimum of Solution Comments a list of numbers from 1 toget from 15 the with initial every list position in the game. Then the goal is to to its permutation by a sequence of allowed moves. addition, one more toothpick is removed from the central 1 color the cells of the board inwill two be alternating colors as those in a chessboard, there and-conquer strategy. Interestingly, solving this puzzle for Algorithmic Puzzles 230 nti quartet: this in ubro etclsie naysqec ovn h uzewudhv ob even be to have would the puzzle and the solving slides sequence horizontal any of in slides number vertical the both of Therefore, number in location positions. same goal the and occupies initial square the empty the puzzle, our In square. empty same the one, opposite well. as the swaps to such three parity for Since the true parity.) is changes position’s outcome numbers the are on adjacent they slide of vertical rules, swap a puzzle’s of one the impact the to out according figuring for done useful be cannot swaps these (Although FIGURE nesos 3 ) 3 ) 2 ) n 5 ) ic sa vnnme,permutation number, be even an to is 4 said Since is 4). (5, 32154 and 1), (2, four 1), are (3, there 2), 32154 (3, permutation inversions: for example, For number one. the smaller a counts precedes one element permutation, a of its parity the of find to general, In positions. orcneuieeeet ntepruain o xml,teodrn ftiles of the ordering change the of example, not shift m for cyclical l, does k, permutation: a slide j, creates the tile horizontal in a A elements of of slide consecutive it. slide vertical four to vertical A parity. a next its and location hence and slide empty permutation horizontal the a a moves. to of moves: game’s parity tile of the the a kinds by how two investigate change allows now may puzzle us position The Let board’s even. a is representing (2) permutation and odd, is (1) parities: one. opposite the to parity adjacent its general two changes of following permutation swap a The a in 4). important: elements (5, but obvious and is 1), parity (3, permutation’s a 1), (2, of property inversions: of number odd an has h aeccia hf a lob bandb he wp fajcn elements adjacent of swaps three by obtained be also can shift cyclical same The the consider to useful is It ti ovnett nepe h aesmvsa euneo ldso the of slides of sequence a as moves game’s the interpret to convenient is It eunn oorpzl,nt htteiiiladfia oiin aedifferent have positions final and initial the that note puzzle, our to Returning m i ... inversions 4.105 nFgr .0 becomes 4.105 Figure in jklm j mato ldn fthe of sliding of Impact ... hc r ar fiseeet htaeoto re:alarger a order: of out are that elements its of pairs are which , → n k even. ... nteohrhn,pruain214is 23154 permutation hand, other the On kjlm l ... parity ,l ,j. m, l, k, j- iedown. tile → fpruain ersnigteboard’s the representing permutations of ... kljm ... m i → ... j klmj ... n k odd ic it since , l 231 Solutions . n ,isone move to the target , not 1 − n Boss Puzzle Therefore, repeating . 1 − and the n ) where the target can n boards. n 14–15 Puzzle × n , also known as the 1, the shooter will definitely hit the target. − n The puzzle is solved by comparing parities of its initial and final 1) since these are the only shots that can guarantee either hitting the 2 shots described above, because its locations and those of the shots Let us start by numbering the hiding spots left to right from 1 to ,... , − − 5 n Fifteen Puzzle n , The If before the first shot the target was at an odd-numbered spot, it will not be hit While no odd permutation is solvable, every even permutation is, although will move to a spot with the same parity as the parity of 146. Hitting a Moving Target of the best known puzzles, rarelycaused missed in a general world-wide puzzle collections. craze Thewho in puzzle could 1880, solve this partly (unsolvable) fueledattributed problem. to by The Sam a invention Loyd (1841–1911), of $1000 the theand offer foremost puzzle a American to is prominent inventor chess often anybody of composer. puzzles Thishowever, attribution, incorrect: promoted the by Loyd puzzle himself, was is, inventedof by Canastota, Noyes New Chapman, the York, Postmaster application who was rejected, applied likely because for of its a similarity toearlier the patent to patent Ernest granted in U. 2 years Kinsey. March For 1880. detailspuzzle, of see The this the story patent monograph and by many J. other Slocum facts and about D. the Sonneveld [Slo06]. by the target or ensuring a spot (1 or, respectively, after the first shot.in We will an consider even-numbered first spot. thetarget case Then when or after the the the target target first wasor moved originally shot, equal to either to a the 3. spot shooter Therefore,either labeled if hit hit the with the the shooter target an makes or oddeven his guarantee number number that second greater than greater the shot or target than equal at to will spotspots 4. be 4 Thus, 3, by at he continue a shooting will at spot consecutive labeled with an will always have the opposite parities. But after the shot at spot Solution It is reasonable for the gunnerat to spot make the first shot at spot 2 (or, symmetrically, Comments to compensate each slide to the righta with slide a down. slide Since to neither the horizontal leftchange slides and the nor each an position’s slide even up parity, with number the ofsame parities vertical for of slides the initial puzzle and to goal havecase, positions the a must puzzle solution. has be no Since the solution. this necessary condition fails in our positions, which is a standard applicationalgorithm of the analysis invariant techniques idea for (see the awe tutorial discussion add on and the row other number examples). to Noteremain the the number that same of if after inversions, a the vertical parity slideempty of of square this a as sum tile having would number as 16. well. Another option is to treat the devising an efficient algorithmfinding to the do shortest sequence this of moves is leadingespecially to a hard a (NP-complete) rather solution for has difficult the been proved task. to In be particular, Algorithmic Puzzles 232 igaso iue416cncranyb iwda necleteapeo the of example excellent an transformation as the viewed using be strategy. hand, change certainly representation other can the 4.106 On Figure solution. of diagrams this in monovariant a of h ymti euneo ht itn osctvl spots consecutively hitting shots of sequence symmetric the Solution Comments Row FIGURE ilgaatehtigtetre nti aea well. as case this in target the hitting guarantee will optto n19 n ulse in published and 1999 in competition mosbe(hw yteXs oain o h oigtre eoethe before location. target the around moving ring the the by for indicated locations is shot X’s) the by (shown impossible urneshtigtetre o any for target the hitting guarantees mosbepstoso h agtbfr ahso for shot each and before target possible the show of diagrams positions The impossible 4.106. Figure in shown diagrams transformation well. as problem the solve spot 4.Ht ihNumbers with Hats 147. X X X 1 h rbe’ ntnefor instance problem’s The osmaie h euneo 2( of sequence the summarize, To hsslto a encl lutae n,i at eie rmthe from derived fact, in and, illustrated nicely be can solution This i , i 4.106 2 X = X 1 h ahmtcascnwntebta follows. as bet the win can mathematicians The .., ,... lutaino the of Illustration h ubro pt tl vial o h agtpasterole the plays target the for available still spots of number The X 3 X 2 n 2 − , X 4 X 3 4 .., ,... , eit h osbe(hw ytesalbakcrls and circles) black small the by (shown possible the depicts X X itn oigTarget Moving a Hitting X 5 n n = − 1 00wsofrda usa mathematical Russian a at offered was 1000 n n , vn in Kvant − > n )sosa h pt numbered spots the at shots 2) − X 2 1 X X X . 1 , When 00(o ,p 21). p. 2, (no. 2000 n − 2 X X X 2 n loih for algorithm . , ... , n = = 3 X X 2 X , and 5 w ht ttesame the at shots two 2 n − X 4 X X n n 1 = , = n 6 and 5 − i . hso;the shot; th X X X 5 2 .., ,... n = X 6 X X X 6 2 . 233 Solutions 1, − say, in n , Rainbow 1 − . n n computes the sum are between 0 and , ) mod j j 1 x x − + n j and 2) S j ( ≤ h = i . = , j so that . i Since the remainders of dividing n j n ≤ n . = 1 n − mod ) mod n i S ) mod j S h ≤ = Correctness of the guess ) mod − i i n + i and since both x j ( be the sum of the numbers on all the hats. ≤ i , S x + ( n n = i mod h i S j = x ( i n S mod th mathematician, 0 j i x 5 and the hat numbers be 3, 4, 0, 3, 2. Then we have the i for every 0 mod = i S +···+ = run the entire range of nonnegative integers from 0 to h n is computed as the remainder of division of the difference 2 n on several Internet sites and in books devoted to technical n i = ih + 33 9 442104 no no 03 9 114 8 32 0 no 12 no 0 yes ( h x i n S mod + 1by j . In recent years, the puzzle has appeared under the names j 1 h = h h − mod S j 88 Hats n = = th mathematician who will guess correctly his/her number. Indeed, j = j x S j , and 1 ,... , Let For example, let Beforehand, they assign themselves sequential numbers from 0 to 1 of these numbers and guesses his/her hat’s number as the smallest nonnegative − , i alphabetical order of their names. Then on seeing theother numbers mathematicians, on the the hats of all the 0 interview questions (e.g., [Zho08,its p. origin. 31]). We have been unable to determine between the mathematician’s sequential number andall the the other sum hats of by the the total numbers number of on the mathematicians.) S following table: inclusive, there will exist exactly one such integer Hats solution to the equation Obviously, n Comments This implies It is the (In other words, which is Algorithmic Puzzles 234 epciey h elslce ob use sidctdb rs.Teci obe to coin The circles, cross. white a coin. and that by around circle black indicated extra an is as by shown guessed is shown prisoner be first are the to by over configurations selected turned cell initial the the respectively; in coins heads-up vr o o obto.Let bottom. to top row every board ensure the done. to be for can function coin it the one how of is turn value Here to the him. compute to is presented to task simply A’s is tails-up task cell. the B’s selected all mapping; the of the of locations location the the maps into that do function coins More To up. a jailer. tails find say, the turned, should by coins they the selected of specifically, cell locations the the of of advantage take location can the they this, B prisoner signal to coin one Solution Freedom for Coin One 148. FIGURE elslce ytejie.Let jailer. the board by the selected cell on coins tails-up with let cells A; the to presented all to assigned numbers sequential the of (If ubrasge oteci ob undoe yA ofind To A. by by denoted over (XOR, turned or” be to coin the to assigned number 24 56 48 40 32 16 8 0 o xml,frtebadi iue4.107a, Figure in board the for example, For is,nme h or’ el rm0t 3 o xml,giglf orgtalong right to left going example, for 63, to 0 from cells board’s the number First, n = 0 4.107 , easm that assume we h rsnr aet eieamto htwl lo rsnrAt turn to A prisoner allow will that method a devise to have prisoners The w ntne fthe of instances Two T T T T (a) 4 3 2 1 J eis6btbnr ersnaino h ubrasge othe to assigned number the of representation binary 6-bit its be = = = = ⊕ 17 13 50 2 opeeto h sum the of complement ) T 10 10 10 10 T T ======X ⊕ T O ete6dgtbnr ersnaino h sequential the of representation binary 6-digit the be 010001 000010 001101 110010 101100 1 X , , h l-eobtsrn,adhence and string, bit all-zero the T n onfrFreedom for Coin One = 2 63 55 47 39 31 23 15 .., ,... 7 J or 56 48 40 32 24 16 X 8 0 T J = n = ete6btbnr representations binary 6-bit the be T 25 ⊕ T 10 = J . = T uze al-pcisand coins Tails-up puzzle. 1 011001 ⊕ (b) X T n h “exclusive the find , 2 X ⊕···⊕ = O ⊕ T J n = to (1) 39 31 23 15 63 55 47 J 7 . J ) : 235 Solutions ?In n ≤ . Indeed, i i S T . Fortunately, ≤ . . ⊕ 10 n . n 10 T 17 . 10 T 25 10 = 53 i = 3 T 61 = T ⊕ 111101 = ⊕···⊕ i = 1 for any bit string ⊕···⊕ T = + 1 i O 011001 + ⊕ T 10 i . 110101 = n n T = ⊕ 61 111101 T T S = 1 010001 J ⊕ = − = ⊕ i i = = J S T T X th tails-up coin for some 1 i ⊕ , prisoner B will get the same location of i 1 011001 ⊕ ⊕···⊕ ⊕···⊕ T − i 110010 1 1 T ⊕ 111101 T + + ⊕···⊕ = i i ⊕ = 1 J ⊕ T T T X ⊕ ⊕ ⊕ 110010 001101 010001 000010 101100 computed by formula (1) is turned heads up. Then 1 1 ⊕ to the other tails-up coins. But what if the coin at that 101100 T = = = = = − − n i i X X 001101 ⊕···⊕ = = T 101100 T T T 10 10 10 10 1 J ⊕ 2 X T = 50 13 17 ⊕ J = = = = = T ⊕ X 1 2 3 4 ⊕···⊕ = T T T T ⊕···⊕ ⊕···⊕ T 000010 ⊕ 2 1 1 X = T T T T X ⊕ = = = 1 J T For example, if the jailer selects cell 61 on the board with the same four tails-up The above example demonstrates the first of the two possible cases—the case this case, turning that coin overthe makes location it of the heads selected up, cell as leaving prisoner B to compute if prisoner A computes coins (see Figure 4.107b), location is already tails up, that is, it is the turning it over indeed adds where the coin at location the selected cell as the one used by prisoner A: and formula (1) works in this case as well because After prisoner A turns thewith coin the at tails-up cell coins 17 at heads locationsthe up, 2, selected prisoner cell 13, as B and will 50 and see will the compute board the location of So, after prisoner A turnsboard the with coin the tails-up at coins location at locations 53 2,location tails 13, of 17, the up, 50, selected prisoner and cell 53 as B and will will compute see the the and hence Algorithmic Puzzles 236 4.Pbl Spreading Pebble 149. puzzle websites. the several then, on Since above given solution. form its the for in were appeared algorithm participants has complete its a but provide 2007, to of asked Fall not the in Towns of Tournament Mathematics numerals. binary of utility hc a ecmue ysmigu h egt nec o—seult 4: to equal row—is each in weights the up summing by computed be can which Solution Comments FIGURE nteboard, the on yafiiesqec falwdmvs od hs ewl sint ahcl ( cell each to assign will we this, do To moves. allowed of sequence finite a by Spreading ouinfor solution a d = o ewl hwta osaraeregion staircase no that show will we Now for puzzle the solves move first legitimate only The h n-iesoa eso ftepzl a fee tteInternational the at offered was puzzle the of version one-dimensional The oeta l h el nthe on cells the all that Note (1 1 + = = , 2 4.108 1 2 1 .., ,... / puzzle. · − 2 1 h uzehsaslto nyfor only solution a has puzzle The 1 + 1 − euneo oe ren h tics region staircase the freeing moves of Sequence / n i 1 h uzesslto rvdsoemr xml fteoccasional the of example more one provides solution puzzle’s The 1 , 1 2 / e h aewih,adtesmo h egt faltecells— the all of weights the of sum the and weight, same the get = j / 4 + ≥ 2 +··· 2. = 1 1 − 1 , 4 / h weight the . 1 ) 2 / + 2 (1 +···+ / 2 + w 1 d 1 ( 1 / hdaoa ihteequation the with diagonal th i − / 4 , 2 +··· j 1 ) j − / = 1 2 ) +···= 2 +···+ 2 n S − n i = − for j and 1 2(1 Fgr 4.109). (Figure (1 n > / + n 2 n j 1 a efedo pebbles of freed be can 2 = − S / = 1 2 2 1 + sae)i the in (shaded) +··· . 2 iue418shows 4.108 Figure 1 . / 2 1 j / +··· i 2 + j − j 1 ) = +··· +··· d Pebble + ) i , 1, j ) 237 Solutions 3 R 1): )is j , + i where j . n , 4 i S / 3 puzzle. would have to = 4 can be freed , ) and ( ) j ≥ 8) n , / R n 1 1 ( j · composed of a finite − + W n 4 i i R . The latter can be found j + − where 4 S 4 n 2 2 Pebble Spreading / S no staircase region 1 from the weight of all the cells · , 4 4 S 3 ≥ + 2 n / 1 · 2 1 for were transformed to occupy some region . + 3 3 < 1/41/4 1) S + ) (1 j 4 + i R − ( ( 4 − 2 W . The total weight of that region, 2 = 2 n S ≤ ) + 1/41/4 1/21/2 4 ) ) j S n ( + cannot be freed from its pebbles either. To prove this, we note R 1 ( 3 W + S i ( W 1 − 1 − Weights assigned to the board’s cells in the 2 4 1/41/4 1/21/2 2 A single move—and hence a finite sequence of moves—cannot change . < = 1 ) 4.109 ) 1 2 3 i j 4 ≥ + R 4 can be freed from pebbles by a finite sequence of moves. i n ( ( Thus, since This immediately implies that no staircase region The staircase − ≥ W 2 number of cells outside that the first row andTherefore, first if column all of the pebbles the from board always contain one pebble each. n the position’s weight, because the weight of a pebble removed from cell ( on the board (Figure 4.110a): compensated by the weights of the new pebbles in cells ( be smaller than the total weight of all the cells outside by subtracting the weight of the cells composing from pebbles by aposition finite the pebbles sequence would of have moves. occupied some If region it were possible, in their final 2 We can then define thecells weight occupied of by a the position pebbles. asany The the weight sum of of the the initial weights position of is all equal the to 1 for FIGURE Algorithmic Puzzles 238 ilfis u h e tc eoeteohr n hn fi ssalrta h next the than smaller is it if then, We and stack. others new the a before in stack taken new order the the put in first coins the will from these taken puts is stack—and generality, each of from of loss coin bottom without one assume, taking may stacks, we such them—which of of row each the through goes algorithm the iteration, 5.BlainSolitaire Bulgarian 150. issue. 1982 July magazine’s the in puzzle the of generalization Kvant the in Conway J. by used that to (#132). similar is solution this in h pe on for bound upper The hsipistefloiguprbudfor bound upper following the implies This outside FIGURE Solution Comments Since rtclm,adaset a and column, first egto h hl udatadtewihso h el ntefis oun the column, first the in (2,2): cells cell of the weight of the weights and row, the first and quadrant whole the of weight puzzle. o tics region staircase for 1 2 3 4 h uzewspooe yM oteihi h oebr18 su of issue 1981 November the in Kontsevich M. by proposed was puzzle The 1/2 1/4 1/8 1 1 W p 1 rbe 75;A hdlvpoie ealdslto oada and to solution detailed a provided Khodulev A. M715); Problem 21, (p. 4.110 S ( 3 R , 1/4 1/2 R 3 1/8 ti ovnett hn fec iea tc fcis neach On coins. of stack a as pile each of think to convenient is It W ) 2 3 a egt fteclsfrsaraeregion staircase for cells the of Weights (a) < h nain datewih ftecretposition—exploited current the of weight idea—the invariant The ol aebe opsdo n eli h rtrw n eli the in cell one row, first the in cell one of composed been have would ( Q 1 3 1/4 1/8 S , ) (a) 3 3 h ebe of pebbles the < lstootieclsi o n oun1i the in 1 column and 1 row in cells outside two plus Q 4 W W 1/8 3 −[ 4 ( fclsi h te osadclms(iue4.110b). (Figure columns and rows other the in cells of ( Q R 1 3 3 a ecluae stedfeec ewe the between difference the as calculated be can ) ) + < 2(1 S 1 3 / / antb rnfre ooccupy to transformed be cannot 8 2 + + 1 1 1 2 3 4 / W / 8 4 ( 1/2 1/8 + 1/4 +··· R 1 1 3 3 ): / 4 1/2 1/4 ) = S 2 + 4 1 n b egt ftecells the of weights (b) and 1 . / 1/4 4 oiar Army Solitaire (b) 3 ]= 3 1/8 ebeSpreading Pebble / 4 4 . R 3 . puzzle 239 Solutions , k , into s n +···+ 2 + 1 ≥ ··· ≥ d e h 2 = n n h g j i d i h c ≥ coins, the algorithm will 1 n n d c b e g b c b a d i b j i f a h c f a e j g f j g f a e into a sum of positive integers (pile ), where s 1). This partition is a one-state loop: n n ,... , ,... , 1 2 n − , 1 k example. The last iteration requires sorting of the piles. n , k e j h h j e d i c i d g Bulgarian Solitaire g h g f j i f e j h c f f 4.111 c b a d c b a g b a e d i b a Since the number of ways to partition the algorithm transforms it intoif itself. the There algorithm is no transforms other ( one-state loop. Indeed, sizes) is finite, theiterations. algorithm Our task will is to have show to that for enter any initial a partition of loop after a finite number of always reach the partition ( including the possibility of starting with a single pile of FIGURE one, insert it in itsnonincreasing proper order place of in the the pilewhere pile the sizes. row coins This are to labeled process have by is letters. the illustrated entire in row Figure sorted 4.111, in Algorithmic Puzzles 240 enotie eg,[r9].I atclr thsbe rvdta omr than more no that proved been has it k particular, In have [Gri98]). variations (e.g., year its and obtained a game been published this about was results which interesting several Brandt, then Jørgen Since earlier. mathematician Danish the by paper a American Scientific onspsto nissakcutn rmtesaksbto.Freape the the example, and 4.111: Figure For number in partition bottom. stack starting stack’s the its a in the coins of the from to sum assigned counting are the by weights stack following to assertion its this equal in prove coin position can each One coin’s to loop. a weight within a happen assigning can sorting pile no First, hc a eesl ovdb akadsubstitution: backward by solved easily be can which ( Comments fsrigo h upti o eurd h weight the required: not weight is the output change see not the to does easy of partition is sorting It a if 41. to is operation 4.111 algorithm’s Figure the in applying partition For that it. starting composing the coins of the all weight of the weights example, the of sum the as sorted) necessarily (not n until on, on nasqec fsae omn op u if But loop. a forming states of sequence a in coins stacks the of 4.111). Figure sorting in requiring iteration situation last the steps—the (see of number finite a after stacks the on coin the ignl utb ul ned fteewr ociso the on coins no were there if Indeed, full. be must diagonals ubro on ol aebe o agrta 1 than larger not been have would coins of number eo h aesz) qaigtecrepnigcmoet ftetotuples two the equations of linear components of corresponding system the a Equating yields size). same the of be position ob ula rvdaoeadtettlnme fciswudhv enlarger been have would coins of number total the and 1 above then proved as full be to n nta one. initial any ags opnn ntescn ul and tuple second the in component largest hr eeaci nte( the on coin a were there ignl ned fi eepsil,teepyso nte( the on spot empty the possible, were it if Indeed, diagonal. mt pt fay(e iue411fra xml) u hn fw aea least at have we if then, But the example). on an for coin diagonal’s 4.111 one the Figure do (see as any diagonal, if its along spots circles empty coins the of each sorting, require not happen can then sorting partitions. size, no coin of their Hence, loop weight. of a within partition’s order the nonincreasing decrease in does not them are sorting partition a composing stacks if s (1 2 , o ewl hwta hr xssn opcnann oeta n partition. one than more containing loop no exists there that show will we Now hsimdaeyipista nytelretdaoa a aesm missing some have can diagonal largest the only that implies immediately This eod naysqec fci attospoue yteagrtmta does that algorithm the by produced partitions coin of sequence any in Second, − n + 1 k − + 1) trtosaerqie orahtesal atto ( partition stable the reach to required are iterations j n 1 , 2 1 eoe ( becomes , b +···+ n = (1 2 ugra oiar a ouaie yMri ade nhis in Gardner Martin by popularized was solitaire Bulgarian − n + d 2 hdaoa ol aerahdtesm egti hi respective their in height same the reached have would diagonal th d 1 + 2) hdaoa,w anthv n mt pt nte( the on spots empty any have cannot we diagonal, th .., ,... ouni 93(e lo[a9b p 64].I a ae on based was It 36–43]). pp. [Gar97b, also (see 1983 in column .., ,... 1 k i hs ehv h igepriinlo o such for loop single-partition the have we Thus, . + = 1) n k k s j − and (4 + + 1 − ( + )hdaoa,altesalrdaoaswudhave would diagonals smaller the all diagonal, 1)th s j − = )adtetotpe r h same, the are tuples two the and 1) ) hnw a en h egto partition a of weight the define can we Then 1). )if 1) k n . 1 = j > s n s and and 1 = ohrie h ulswudnot would tuples the (otherwise, 1 n i j n = + + i = + n n i 2 s i 1 − − if j +···+ 1 1 + j faci nstack in coin a of k − = d = k , 2 hdaoa,tetotal the diagonal, th − k for 1 n +···+ 1 − s , )hdaoa and diagonal 1)th + epciey But respectively. 1 ( k .., ,... 1 i s − = = utb the be must n k ’s. ) n if And 1). 2 ,adso and 2, l the all , d .., ,... )from 1) − i 1)th and s k , References

[Ash04] Ash, J. M., and Golomb, S. W. Tiling deficient rectangles with trominoes. Mathematics Magazine, vol. 77, no. 1 (Feb. 2004), 46–55. [Ash90] Asher, M. A river-crossing problem in cross-cultural perspective. Mathematics Magazine, vol. 63, no. 1 (Feb. 1990), 26–29. [Ave00] Averbach, B., and Chein, O. Problem Solving Through Recreational Mahtematics. Dover, 2000. [Bac12] Bachet, C. Problèmes plaisans et delectables qui se font par les nombres. Paris, 1612. [Backh] Backhouse, R. Algorithmic problem solving course website. www.cs.nott.ac.uk/ ∼rcb/G51APS/exercises/InductionExercises.pdf (accessed Oct. 4, 2010). [Bac08] Backhouse, R. The capacity-C torch problem. Mathematics of Program Construction 9th International Conference (MPC 2008), Marseille, France, July 15–18, 2008, Springer-Verlag, 57–78. [Bal87] Ball, W. W. Rouse, and Coxeter, H. S. M. Mathematical Recreations and Essays, 13th edition. Dover, 1987. www.gutenberg.org/ebooks/26839 (1905 edition; accessed Oct. 10, 2010). [Bea92] Beasley, J. D. The Ins and Outs of Peg Solitaire. Oxford University Press, 1992. [Bec97] Beckwith, D. Problem 10459, in Problems and Solutions, American Mathematical Monthly, vol. 104, no. 9 (Nov. 1997), 876. [Bel09] Bell, J., and Stevens, B. A survey of known results and research areas for n-queens. Discrete Mathematics, vol. 309, issue 1 (Jan. 2009), 1–31. [Ben00] Bentley, J. Programming Pearls, 2nd ed. Addison-Wesley, 2000. [Ber04] Berlekamp, E. R., Conway, J. H., and Guy, R. K. Winning Ways for Your Mathematical Plays, Volume 4, 2nd ed. A K Peters, 2004. [Ber91] Bernhardsson, B. Explicit solutions to the n-queens problem for all n. SIGART Bulletin, vol. 2, issue 2 (April 1991), 7. [Bogom] Bogomolny, A. Interactive Mathematics Miscellany and Puzzles. www.cut-the- knot.org (accessed Oct. 4, 2010). [Bog00] Bogomolny, A. The three jugs problem. The Mathematical Association of America, May 2000. www.maa.org/editorial/knot/water.html#kasner (accessed Oct. 10, 2010). [Bol07] Bollobás, B. The Art of Mathematics: Coffee Time in Memphis. Cambridge University Press, 2007. [Bos07] Bosova, L. L., Bosova, A. Yu, and Kolomenskaya, Yu. G. Entertaining Informatics Problems, 3rd ed., BINOM, 2007 (in Russian). [Bro63] Brooke, M. Fun for the Money. Charles Scribner’s Sons, 1963. [CarTalk] Archive of the U.S. National Public Radio talk show Car Talk. www.cartalk.com/content/puzzler (accessed Oct. 4, 2010).

241 References 242 Gr3 ade,M. Gardner, M. Gardner, [Gar83] M. Gardner, [Gar78] [Gar71] Gr6 ade,M. Gardner, [Gar86] Gr1 ade,M. Gardner, [Gar61] Gr9 ade,M. Gardner, [Gar89] M. Gardner, [Gar88a] F. C. T. Stein, Crack, and L., R. Rivest, E., C. Leiserson, H., T. Cormen, [Cra07] [Cor09] Gr7 ade,M. Gardner, [Gar87] E. H. Dudeney, W. E. Dijkstra, In puzzles. Coin-moving [Dud02] H. Verrill, and L., [Dij76] M. Demaine, of D., number E. Alcuin Demaine, The J. G. Woeginger, and A., [Dem02] C. Hurkens, P., Csorba, [Cso08] Ee0 pro,D .Tinua Od Pennies. (Old) Triangular B. D. Eperson, A. Engel, [Epe70] [Eng99] Gr8]Grnr M. Gardner, [Gar88b] recursion. and Tiling R. Johnsonbaugh, and I-Ping, Chu, weight partial a with coin defective [Chu87] a of Detection F. Hwang, and C., Christen, [Chr84] Dd8 uee,H E. H. Dudeney, [Dud58] Gr9 adnr A. Gardiner, I. Itenberg, and S., [Gar99] Genkin, D., Fomin, K. A. Tolpygo, and [Fom96] L., A. Rozental, A., S. Molchanov, B., E. Dynkin, [Dyn71] Dd7 uee,H .(dtdb atnGardner). Martin by (edited E. H. Dudeney, [Dud67] .H rea,1983. Freeman, H. W. cetfi American Scientific .H rea,1988. Freeman, H. W. 1987. Press, Chicago of University Algorithms .H rea,1986. Freeman, H. W. 405–431. 2002, Press, editor, Nowakowski, J. R. Science Computer in Notes Lecture graph. a Interviews, cetfi mrcnBo fPzlsadGames and 1988. Puzzles of Book American Scientific Bulletin 173–179. information. 02 w.uebr.r/bos265(99eiin cesdOt 10, Oct. 2010). accessed edition; (1919 www.gutenberg.org/ebooks/27635 2002. 96(rnltdfo Russian). from (translated 1996 Experience 48–49. 1970), (Feb. 387 no. Problems Mathematical 1967. Sons, Scribner’s Charles mrc,1989. America, r/bos173(rtpbihdi 97 cesdOt 0 2010). 10, Oct. accessed 1917; in published (first org/ebooks/16713 o.1,ise1(e.18) 261–263. 1987), (Feb. 1 issue 19, vol. , rceig fte1t nulErpa ypsu nAlgorithms. on Symposium European Annual 16th the of Proceedings rbe-ovn Strategies Problem-Solving .Aeia ahmtclScey ahmtclWrd o.7, Vol. World, Mathematical Society, Mathematical American ). r dto.MTPes 2009. Press, MIT edition. 3rd , 0he.Sl-ulse,2007. Self-published, ed. 10th ahmtclPuzzling Mathematical h!Insight aha! ahmtclPuzzles Mathematical er nteSre:Qatttv usin rmWl tetJob Street Wall from Questions Quantitative Street: the on Heard mrcnMteaia Monthly Mathematical American eaeaosadOhrMteaia Diversions Mathematical Other and Hexaflexagons atnGrnrs6hBo fMteaia iesosfrom Diversions Mathematical of Book 6th Gardner’s Martin h eodSinicAeia oko uze n Games and Puzzles of Book American Scientific Second The nte ognt n te ahmtclEntertainments Mathematical Other and Doughnuts Knotted ahmtclCarnival Mathematical icpieo Programming of Discipline A h atruyPzlsadOhrCrosProblems Curious Other and Puzzles Canterbury The ieTae n te ahmtclBewilderments Mathematical Other and Travel Time mzmnsi Mathematics in Amuzements hes ie n te ahmtclAmusements. Mathematical Other and Life, Wheels, .H rea,1971. Freeman, H. W. . r eie dto,Nua 91(nRussian). (in 1971 Nauka, edition, revised 3rd , cetfi mrcnW .Femn 1978. Freeman, H. American/W. Scientific . oeGmso oChance No of Games More o.59,20,320–331. 2008, 5193, vol. , hmsY rwl,1961. Crowell, Y. Thomas . pigr 1999. Springer, . oe,1999. Dover, . h ahmtclAscainof Association Mathematical The . h ahmtclGazette Mathematical The rnieHl,1976. Hall, Prentice . 3 Puzzles 536 oe,15.www.gutenberg. 1958. Dover, . ahmtclCircles Mathematical o.9,n.3(ac 1984), (March 3 no. 91, vol. , nvriyo hcg Press, Chicago of University . abig University Cambridge . & uiu Problems Curious C SIGCSE ACM nrdcinto Introduction : h First The ( o.54, vol. , Dover, . Russian . . . . 243 References , . , , vol. , ACM, , vol. 38, American Mathematical . Basic Books, . W. W. Norton, Proceedings of the and the Return of . www.mcs.surrey. www.puzzles.com/ chessboard. Concrete Mathematics: , vol. 5/1 (June 2000), ... American Mathematical n × n NAW . Nauka, 1978 (in Russian). . Addison-Wesley, 2005. Puzzles.com. American Mathematical Monthly . Nauka, 1976 (in Russian). inroads—SIGCSE Bulletin , July 1982, 28–31, 55 (in Russian). Advances in Applied Mathematics , Nov. 1980, 30–32, 62–63 (in Russian). , 2nd ed. Addison-Wesley, 1994. Kvant . Sterling, 2009. Kvant , vol. 14, no. 3 (May 1982), 109–111. Algorithm Design vol. 73, no. 7 (Aug.–Sept. 1966), 721–725. , vol. 20 (Nov. 1973), 545–549. Polyominoes: Puzzles, Patterns, Problems, and Packings Gödel, Escher, Bach: An Eternal Golden Braid The New Puzzle Classics: Ingenious Twists on Timeless Favorites The Art of Computer Programming, Volume 1: Fundamental Penrose Tiles to Trapdoor Chiphers Springer, 1997. The Last Recreations: Hidras, Eggs, and Other Mathematical Colossal Book of Short Puzzles and Problems In the Kindom of Quick Thinking Fibonacci Numbers and the Golden Section 3rd ed. Addison-Wesley, 1997. Mathematics on the Chessboard , revised edition. The Mathematical Association of America, 1997. All-Star Mathlete Puzzles , vol. 61, no. 10 (Dec. 1954), 675–682. , vol, 76, no. 475 (March 1992), 102–126. 2nd edition. Princeton University Press, 1994. PuzzlePlayground/CoinTriangle/CoinTriangle.htm (accessed2010). Oct. 4, Monthly Arithmetic Teacher no. 2 (June 2006), 21–22. Sterling Publishing, 2005. A Foundation for Computer Science Gazette vol. 110, no. 1 (Jan. 2003), 25–35. compositions under repeated shifts. 21, no. 2 (1998), 205–227. 2003, 11–15. 208–210. 34th SIGCSE Technical Symposium on Computer Science Education 1979. 2006. Mystifications. Dr. Matrix Algorithms, Mathematical Monthly, ac.uk/Personal/R.Knott/Fibonacci/ (accessed Oct. 4, 2010). Information Processing Letters [Gol94] Golomb, S. W. [Graba] Grabarchuk, S.[Gra05] Coin triangle. From Grabarchuk, S. [Gre73] Greenes, C. E. Function generating problems: the row chip switch. [Gol54] Golomb, S. W. Checkerboards and polyominoes. [Hes09] Hess, D. [Ign78] Ignat’ev, E. I. [Gri98] Griggs, J. R., and Ho, Chih-Chang. The cycling of partitions and [Gra94] Graham, R. L., Knuth, D. E. and Patashnik, O. [Iye66] Iyer, M., and Menon, V. On coloring the [Had92] Hadley, J., and Singmaster, D. Problems to sharpen the young. [Gin06] Ginat, D. Coloful Challenges column. [Iba03] Iba, G., and Tanton, J. Candy sharing. [Hof79] Hofstadter, D. [Hur00] Hurkens, C. A. J. Spreading gossip efficiently. [Gin03] Ginat, D. The greedy trap and learning from mistakes. [Gik80] Gik, E. The Battleship game. [Gik76] Gik, E. Ya. [Gar06] Gardner, M. [Gar97b] Gardner, M. [Knu97] Knuth, D. E. [Gar97a] Gardner, M. [Kho82] Khodulev, A. Relocation of chips. [Kin82][Kle05] King, K. N., and[Knott] Smith-Thomas, B. An optimal algorithm Kleinberg, for J., sink-finding. and Tardos, E. Knott, R. References 244 Ku8 nt,D E. D. Knuth, [Knu98] Ke9 rhr .L,adSisn .R. D. Stinson, and L., D. Kreher, M. Kraitchik, [Kre99] [Kra53] Kr2 odmk,B A. B. Kordemsky, S. Wagon, and [Kor72] D., Velleman, E., D. J. Konhauser E. D. Knuth, [Kon96] [Knu11] Lio en,K .M. R. K. Leino, interchanges. adjacent by Permutation H. D. Lehmer, [Leino] semi-invariant. G. Laakmann, the on Etudes B. D. Fomin, [Leh65] and D., L. Kurlandchik, [Laa10] [Kur89] Kr5 odmk,B A. B. Kordemsky, [Kor05] Lv1 emr,S . n ok .E. E. Cook, and X., S. Levmore, A. Levitin, [Lev81] [Lev06] Ly9 od .(dtdb .Gardner) M. by (edited S. Loyd, [Loy59] Ly0 od .(dtdb .Gardner) M. by (edited S. Loyd, [Loy60] Mn9 abr U. Manber, [Man89] Mr6 atn .E. G. Martin, [Mar96] Mc2 ak .R. D. Mack, [Mac92] Mc8 ihlwc,Z,adMcaeiz M. Michalewicz, and Z., Michalewicz, [Mic08] E. Lucas, [Luc83] Mc9 ihe,T S. T. Michael, [Mic09] [MathCircle] [MathCentral] Ms1 ocvc,I 1000 I. Moscovich, Duotaire. and solitaire peg One-dimensional [Mos01] D. Eppstein, and C., Moore, [Moo00] Ne1 Niederman, [Nie01] xoiin,N.1,TeMteaia soito fAeia 1996. America, of Association Mathematical The 18, No. Expositions, Mysteries. Mathematical Intriguing Other And Go?: 1 Part Algorithms, Searching, o ,18,6–8(nRussian). (in 63–68 1989, 7, no. Monthly Search and Enumeration, cinr 92(rnltdfo Russian). from (translated 1972 Scribner, ero,2006. Pearson, 2010). 4, Oct. (accessed puzzles.html obea,1981. Doubleday, 1959. 1989. h ehial Inclined Technically the 2009. 1960. Dover, c.4 2010). 4, Oct. Circle Math The Central. Math 1996. America, of Association Mathematical ulctos4.Srne,20,341–350. 2000, Springer, 42. Publications Games Combinatorial on Workshop MSRI of Proceedings Solving Problem and 2008. Mathematics, Thinking, Critical to oka ulsig 2001. Publishing, Workman o.7,n.2(e.16) 36–46. 1965), (Feb. 2 no. 72, vol. , érain mathématiques Récréations n d dio-ely 1998. Addison-Wesley, ed. 2nd nrdcint h einadAayi fAlgorithms of Analysis and Design the to Introduction nrdcint loihs raieApproach Creative A Algorithms: to Introduction adt-ov ahPuzzles Math Hard-to-Solve h nfca EEBanutrGmbo:Mna okusfor Workouts Mental Gamebook: Brainbuster IEEE Unofficial The ahmtclRecreations Mathematical h r fCmue rgamn,Vlm A Combinatorial 4A, Volume Programming, Computer of Art The aheta.rgn.am acse c.4 2010). 4, Oct. (accessed mathcentral.uregina.ca/mp rcigteCdn Interview Coding the Cracking oymne:AGiet uze n rbesi Tiling in Problems and Puzzles to Guide A Polyominoes: o oGada r Gallery Art an Guard to How h r fCmue rgamn,Vlm :Srigand Sorting 3: Volume Programming, Computer of Art The w.hmtcrl.r/eerhrbespp(accessed www.themathcircle.org/researchproblems.php . Puzzles ero,2011. Pearson, . ahmtclCharmers Mathematical h ocwPzls 5 ahmtclRecreations Mathematical 359 Puzzles: Moscow The lyTik:Pzls aaoe,Ilsos n Games and Illusions, Paradoxes, Puzzles, Thinks: Play EEPes 1992. Press, IEEE . R rs,1999. Press, CRC . research.microsoft.com/en-us/um/people/leino/ . ahmtclPzlso a Loyd Sam of Puzzles Mathematical oeMteaia uze fSmLoyd Sam of Puzzles Mathematical More o.2 atirVlas 1883. Villars, Gauthier 2. Vol. , ue taeisfrPzlsadGames and Puzzles for Strategies Super obntra loihs Generation, Algorithms: Combinatorial uzeBsdLann:A Introduction An Learning: Puzzle-Based n eie dto.Dvr 1953. Dover, edition. revised 2nd , trigPbihn,2001. Publishing, Sterling . nk,20 i Russian). (in 2005 Oniks, . t d aeru,2010. CareerCup, ed. 4th , onHpisUiest Press, University Hopkins John . h ocaiMathematical Dolciani The hc a i h Bicycle the Did Way Which mrcnMathematical American ekly A MSRI CA. Berkeley, , yrdPublishers, Hybrid . Addison-Wesley, . n edition. 2nd , Dover, . Kvant The . , . . . . 245 References , . , 2nd ed. , vol. 45, no. 10 . Dover, 1968 . The American . (Excursions in Microsoft’s Cult of . The Mathematical ? , vol. 78 (Aug. 2002), . A K Peters, 1998. , 73, no. 464 (June 1989), , 6th edition. McGraw-Hill, Communications of the ACM . Princeton University Press, . Wiley, 2007. EATCS Bulletin . Wiley, 2004. . Norton, 2002. . Oxford University Press, 1965. . Prentice-Hall, 1995. Mathematical Miniatures Mathematical Gazette American Mathematical Monthly Cake Cutting Algorithms A New Aspect of Mathematical Method : Mathematical Solitaires & Games , vol. 28, no. 280 (July 1944), 96–103. Sources in Recreational Mathematics: An Annotated How Would You Move Mount Fuji grigsbyj/Rand_Final.pdf (accessed Oct. 4, 2010). The Zen of Magic Squares, Circles, and Stars: An Exhibition Puzzles & Paradoxes Mathematical Journeys Famous Puzzles of Great Mathematicians ∼ Mathematics and Chess: 110 Entertaining Problems and Solutions How the World’s Smartest Companies Select the Most Creative , 8th preliminary edition. www.g4g4.com/MyCD5/SOURCES/ . projecteuler.net (accessed Oct. 4, 2010). The Master Book of Mathematical Recreations Problems on Algorithms Doctor Ecco’s Cyberpuzzles Puzzles for Programmers and Pros — How to Solve It Discrete Mathematics and Its Applications . Little-Brown, 2003. c, M. c, M. sillke/PUZZLES/crossing-bridge (accessed Oct. 4, 2010). ∼ Association of America, Anneli Lax New MathematicalWashington, Library, DC, Volume 2003. #43, 241–246. Bibliography SOURCE1.DOC (accessed Oct. 4, 2010). (translated from Dutch). 2007. (Dec. 1938), 694–696. vol. 15, issue 6 (June 1972), 462–464. Recreational Mathematics Series 1), Baywood Publishing, 1980. Mathematical Gazette America, June 2003.(accessed Oct. 4, www.maa.org/mathland/mathtrek_06_02_03.html 2010). Dover, 1997. Mathematical Society, 2009. of Surprising Structures2002. across Dimensions 73–81. Project Euler www2.bc.edu/ Princeton University Press, 1957. the Puzzle Thinkers Missionaries and Cannibals.” de/ [Sch68] Schuh, F. [Sav03] Savchev, S., and Andreescu, T. [Sch04] Schumer, P. D. [Rob98] Robertson, J., and Webb, W. [Rot02] Rote, G. Crossing the bridge at night. [Sin10] Singmaster, D. [OBe65] O’Beirne, T. H. [Sch80] Schwartz, B. L., ed. [Sco44] Scorer, R. S., Grundy, P. M., and Smith, C. A. B. Some binary games. [Ros38] Rosenbaum, J. Problem 319, [Ros07] Rosen, K. [Par95] Parberry, I. [Pet03] Peterson, Ivar.[Pet97] Measuring with jugs. The Mathematical Association Petkovi´ of [Pet09][Pic02] Petkovi´ Pickover, C. A. [Poh72] Pohl, I. A sorting problem and its complexity. [ProjEuler] [Pol57] Pólya, G. [Ran09] Rand, M. On the Frame-Stewart algorithm for the Tower of Hanoi. [Pou03] Poudstone, W. [Pre89] Pressman, I., and Singmaster, D. “The Jealous Husbands” and “The [Sillke] Sillke, T. Crossing the bridge in an hour. www.mathematik.uni-bielefeld. [Sha02][Sha07] Shasha, D. Shasha, D. References 246 Zo8 hw X. Zhow, P. Winkler, P. Winkler, [Zho08] [Win07] From Problem. Josephus [Win04] W. E. Weisstein, [Weiss] Se4 tihu,H. Steinhaus, [Ste64] Tn1 atn J. Tanton, [Tan01] Te9 wei,M .K rpia ehdo ovn atginmeasuring Tartaglian solving of method graphical A K. C. M. Tweedie, [Twe39] Se6 twr,I. Stewart, I. Stewart, [Ste06] in [Ste04] Egg-Dropping of Joy V. A. Spivak, The 4. Games: www.tutor. OR/MS 2002. [Spi02] Feb. M. problem. Sniedovich, torch and bridge The M. Sniedovich, [Sni03] [Sni02] D. Sonneveld, and J. Slocum, [Slo06] Ti9 rg,C .Ivrigci triangles. coin Inverting W. C. Trigg, olympiads. mathematical Canadian A. G. Tonojan, [Tri69] [Ton89] [techInt] I. Stewart, [Ste09] Ti5 rg,C W. C. Trigg, [Tri85] 2010). 4, Oct. (accessed mathworld.wolfram.com/JosephusProblem.html Resource. i Russian). (in ok,2009. Books, puzzles. 94(rnltdfo Polish). from (translated 1964 48–64. 2003), (Sept. 1 no. Kong. Hong and Braunschweig 2010). 4, Oct. (accessed ms.unimelb.edu.au/bridge Puzzle Greatest America’s How 2006. Years 1880. 115 for of Everyone Fooled Craze Loyd, Sam the Designer, Started That Puzzle The i Russian). (in techInterviews. 2001. America, of Association 2006. Press, University o.2(99,150–152. (1969), 2 vol. ahmtclGazette Mathematical rcia ud oQatttv iac Interview Finance Quantitative to Guide Practical A ov hs ahAtvte o tdnsadClubs and Students for Activities Math This: Solve ahHysteria Math o oCtaCk:AdOhrMteaia Conundrums Mathematical Other And Cake: a Cut to How ahmtclMind-Benders Mathematical Collection Connoisseur’s Puzzles: Mathematical rfso twr’ aie fMteaia Curiosities Mathematical of Cabinet Stewart’s Professor ahmtclQuickies Mathematical n huadadOeMteaia Problems Mathematical One and Thousand One n ude rbesi lmnayMathematics Elementary in Problems Hundred One w.ehneve.r/rhv acse c.4 2010). 4, Oct. (accessed www.techinterview.org/archive xodUiest rs,2004. Press, University Oxford . o.2,n.25(uy13) 278–282. 1939), (July 255 no. 23, vol. , h 5Pzl:HwI rv h ol Crazy. World the Drove It How Puzzle: 15 The NOM rnatoso Education on Transactions INFORMS oe,1985. Dover, . ees 2007. Peters, K A . ora fRcetoa Mathematics Recreational of Journal MathWorld– lcmPzl Foundation, Puzzle Slocum . Kvant 99 o ,75–76 7, no. 1989, , h Mathematical The . ees 2004. Peters, K A . ofa Web Wolfram A dcto,2002 Education, . uucm 2008. Lulu.com, . ai Books, Basic . Oxford . Basic . o.4, vol. , , DesignStrategyand AnalysisIndex

This index groups the puzzles by the design strategies and analysis questions. The puzzles used in the tutorials are marked by “tut”; all the other puzzles are indexed by their number in the main portion of the book. Some of the puzzles are listed in more than one category.

ANALYSIS Output Analysis tut Chess Invention tut Square Build-Up 6. Predicting a Finger Count 17. A King’s Reach 26. Find the Rank 31. The Three Pile Trick 52. Counting Triangles 55. Odometer Puzzle 57. Fibonacci’s Rabbits Problem 66. Remaining Number 68. Digit Sum 77. Searching for a Pattern 79. Locker Doors 100. A Knight’s Reach 120. Penny Distribution Machine 141. The Josephus Problem

Step Counting tut Tower of Hanoi 2. Glove Selection 19. Page Numbering 32. Single-Elimination Tournament 61. Checkers on a Diagonal 120. Penny Distribution Machine

247 Design Strategy and Analysis Index 248 5.BlainSolitaire Bulgarian Life of Game 150. The 133. 4.TeFfenPuzzle Fifteen The Revisited Tiling 145. Domino 112. 0.Jmigt h te Side Other the to Jumping 103. Double- Hare the and Fox 109. The 107. 0.Double- 109. Parity INVARIANTS Other tut Invariants Other Coloring .RwadClm xhne o n ounelements column and row Exchanges Column and Row 5. 1 oiotladVria Dominoes Vertical and Horizontal Chase 91. Rooster Planning 73. Exhibition Walks 47. Board Journey Corner-to-Corner 39. A 18. Sort of Reversal Dominoes Vertical and 99. Horizontal Glasses Down 91. Upside Sectors on 87. Chips Number 69. Remaining Minuses and 66. Pluses Diagonal a on 63. Checkers Ball 61. Last Tiling 50. Tetromino Tracing 38. Figure 28. 7 h aeo Topswops of Game The Battleship a 97. Hitting Sectors on 93. Chips Minuses and 69. Pluses Recruits Up 63. Lining 56. tut tut tut tut raigaCooaeBar Chocolate a Breaking hcesi h Corn the in Chickens Chessboards Deficient of Tiling Domino Problem Bridges Königsberg The Chessboards Deficient of Tiling Domino n n Dominoes Dominoes ubro pieces of number 249 Design Strategy and Analysis Index Celebrity Problem The n-Queens Problem 8. Jigsaw Puzzle Assembly number of pieces 3. Rectangle4. Dissection Ferrying Soldiers bottom-up tut 15. Tromino40. Tilings Four92. Alternating Knights Trapezoid96. Tiling Tiling a clockwise Staircase order Region divisibility by 3 divisibility by 3 divisibility by 3 22. Team32. Ordering Single-Elimination33. Tournament Magic42. and Pseudo-Magic The43. Other Wolf-Goat-Cabbage Puzzle Number46. Placement bottom-up Tricolor59. Arrangement Hats65. Of Two Colors bottom-up Code68. Guessing Digit81. Sum Celebrity82. Problem Revisited Heads83. Up Restricted86. Tower of Hanoi Rumor90. Spreading II bottom-up Seating94. Rearrangements Searching a Sorted Table bottom-up bottom-up tut Decrease-by-1 DECREASE-AND-CONQUER BACKTRACKING 104. Pile105. Splitting The110. MU Puzzle The120. Chameleons Penny132. Distribution Machine The143. Solitaire binary Army representation Infected149. Chessboard sum of the divisibility products by Pebble 3 Spreading differences mod 3 position weight (monovariant) region’s perimeter (monovariant) position weight 27. The29. Icosian Game Magic70. Square Revisited Jumping into Pairs I 106. Turning107. on a Light Bulb The Fox and the Hare Design Strategy and Analysis Index 250 4.KligSquares Killing Switches 144. Security Solitaire 128. One-Dimensional 117. 2.Rv’ Puzzle Reve’s 129. 4 by Puzzle Counter Tait’s 131. Double- 109. Decrease-by-another-constant Decrease-by-2 bottom-up Coloring Point Fairly Cake a 134. Dividing Dots 126. Crossing Removal 114. Coin 113. Decrease-by-variable-number Decrease-by-constant-factor 1.BeCutn atro 2 of factor 2 of factor Problem Josephus The Counting 141. Bye 116. 4 ack Sorting Pancake Tracing 84. Figure Problem Flag National 28. Polish 23. 6 by 8 by 3 Region by Staircase a Tiling 4 Tiling by Tromino 96. Straight Octagons 78. Creating Numbers 64. McNugget 48. bottom-up bottom-up Glasses Down Upside II Cells 87. Marking I Cells 72. Marking I Pairs into 71. Jumping Pancakes 70. Making 16. 4 utn etnua or atro 2 of 2 factor of factor 3 of factor 2 of factor 2 3 of or factor 2 Board of Rectangular factor a Cutting Scale Spring a with Detection 54. Fake-Coin Tournament 53. Single-Elimination Trick Pile Three 32. The Stick a 31. Cutting Coins Eight Among Fake 30. A 10. tut ubrGuessing Number n Dominoes atro 2 of factor 251 Design Strategy and Analysis Index -Counters Problem n Shortest Path Counting Tromino Puzzle Non-Attacking Kings Bridge Crossing at Night tut tut 13. Blocked20. Paths Maximum62. Sum Descent Picking98. Up Coins Palindrome Counting 38. Tetromino64. Tiling Creating78. Octagons Straight80. Tromino Tiling The91. Prince’s Tour Horizontal92. and Vertical Dominoes Trapezoid95. Tiling Max-Min96. Weights Tiling a Staircase Region 15. Tromino37. Tilings 2 tut tut tut Magic Square GREEDY APPROACH EXHAUSTIVE SEARCH DYNAMIC PROGRAMMING DIVIDE-AND-CONQUER 24. Chessboard34. Colorings Coins45. on a Star A67. Knight’s Shortest Path Averaging73. Down Rooster76. Chase Efficient85. Rook Rumor Spreading I 15. Tromino35. Tilings Three Jugs 104. Pile Splitting 101. Room113. Painting Coin119. Removal Colored132. Tromino Tiling The Solitaire Army Design Strategy and Analysis Index 252 4.HtigaMvn Target Moving a Hitting Table Round Arthur’s 146. King Sharing 139. Candy Pacification 138. Parliament 122. ntneSimplification Instance TRANSFORM-AND-CONQUER IMPROVEMENT ITERATIVE Tour Knight’s The Cutting 127. Chain Testing 124. Super-Egg Weights 121. Bachet’s Route Longest 115. The 108. ersnainChange Representation 3.TeSltieArmy Solitaire The Counting 132. Bye 116. 8 ii u dedrearrangement addend digits binary two last difference, sums’ two Pattern a for Searching unfolding graph Sum 77. Digit graph state-space unfolding Number 68. graph Missing graph, Cannibals and 51. Missionaries line numbers real coin Knights the by Alternating 49. on stacks Four intervals Star a on 40. Coins Alive Be to Time Best 34. The Coins Fake of Stack 25. A 11. tut tut tut tut 2 ed Up Heads Down 82. Averaging 67. 4 raigOtgn presorting presorting even to odd Octagons Creating Arrangement 64. Tricolor Placement 46. Number Dissection 43. Square 21. .Mna rtmtcadn rearrangement addend Arithmetic Mental 9. tut tut tut .Rcag iscinodt even to odd Dissection Rectange 3. nga Detection Anagram ahEnvelopes Cash w elu Husbands Jealous Two urn’ Puzzle Guarini’s nga Detection Anagram Changes Positive Placement Stand Lemonade presorting “signatures” binary tt-pc graph state-space rp,gahunfolding graph graph, 253 Design Strategy and Analysis Index to a math problem Dominoes to the Euler circuit problem n -Queens Problem Revisited n Optimal Pie Cutting 1. A7. Wolf, a Goat, and a Cabbage Bridge Crossing at Night tut 74. Site89. Selection Counter92. Exchange Trapezoid Tiling to 1D Toads and to Frogs a math problem to a whole triangle 12. Questionable14. Tiling Chessboard27. Reassembly The36. Icosian Game Limited38. Diversity Tetromino41. Tiling The44. Circle of Lights Lighter58. or Heavier? Sorting60. Once, Sorting Twice Squaring75. a Coin Triangle Gas88. Station Inspections Toads and Frogs 142. Twelve147. Coins Hats with Numbers 111. Inverting a Coin Triangle to a math problem 102. The109. Monkey and the Coconuts Double- to a math problem OTHER Problem Reduction 106. Turning115. on a Light Bulb Bachet’s118. Weights Six120. Knights bit string Penny125. Distribution Machine Sorting130. 5 binary in 7 Poisoned135. Wine binary & ternary Different136. Pairings Catching146. a Spy graph, Hitting148. graph a unfolding Moving Target One Coin for Freedom points on binary the real table, line points on diagram a circumference binary integer pairs 123. Dutch137. National Flag Problem Jumping140. into Pairs II The IndexofTermsandNames

Aanderaa, S. O., 150 Bogomolny, Alexander, 110, 154, 159, 160 Alcuin of York, 12, 82, 121 Bollobás, Béla, 227 algorithm Brandt, Jørgen, 240 nonrecursive, 24 breadth-first search, 110 recursive. See also recursive algorithm Bridge and Torch problem, 87 algorithm analysis Brook, Maxey, 185 index of applications, 247–249 Bulgarian solitaire, 70–71 techniques of, 22–31 buttons and strings method, 14, 108 algorithm design index of applications, 249–253 strategies of, 3–22 card puzzles, 39, 46, 55 algorithm efficiency ceiling (mathematics), 9 class of. See rate of growth Chapman, Noyes, 231 optimal, 9, 27, 30, 86–87, 88–89, 105, Chein, O., 89, 207 125, 129, 153, 156, 157, 183–186, chessboard problems, 23, 28, 35, 41, 57, 60, 199–202, 219 67, 68 worst-case analysis of, 52, 59, 83, 125, bishop, 37 150, 154, 165, 167, 179, 198, king, 16, 36, 37 202, 226 knight, 14, 36, 37, 42, 43, 57, 62, 64 anagram, 11 prince, 51 Andreescu T., 199 queen, 6, 67 Averbach, B., 89, 207 rook, 37, 51 Chinese Rings, 179, 180, 207 Christen, C., 125 Bachet, Claude Gaspar, 106, 190 Chu, I-Ping, 196 Backhouse, Roland, 87, 164 Church, Alonzo, 129 backtracking, 5–8 coin problems, 52, 60, 69. See also weighing index of applications, 249 problems backward substitutions, method of, 138, 150, coloring (invariant), 28, 248 151, 176, 177, 197 combination (mathematics), 8, 22 backward thinking, 197, 219 convex hull (mathematics), 135 Ball, W. W. Rouse, 106, 139, 159, 160, 182, Conway, John Horton, 170, 212, 213, 215 207, 225 Cook, E. E., 87 Beasley, John D., 193, 212, 213 Coxeter, H.S.M., 106, 139, 159, 160, Beckwith, D., 188 207, 225 Bell, J., 223 cutting problems, 15, 30, 32, 37, 39, Bellman, Richard, 20 45, 63 Bernhardsson, B., 223 binary numbers, 11–12, 146–147, 189, 191–192, 197, 209, 225, 234–236 De Moivre, Abraham, 205 binary search, 209 dead end, in a state-space tree, 6, 7 Boardman, J. M., 212 decimal numbers, 11, 36, 146 Boerner, Hermann, 128 decision tree, 89, 225–226

254 255 Index of Terms and Names path problems, Dirac’s theorem; See also See also 165, 187 Euler circuit; Euler path; Hamilton circuit; Hamilton path; multigraph Hamilton 209, 233 coloring, 248 other, 248–249 parity, 248 applications of, 252–253 directed, 12 edge of, 12 state-space, 12–14 undirected, 12 unfolding of, 14–15 vertex of, 12 index of applications, 251–252 index of applications, 248–249 Gates, Bill, 154 Gauss, Carl Friedrich, 22, 82, 88, 205 Gibson, R., 175 Gik, E., 97, 146, 172 Ginat, D., 223 Golomb, Solomon W., 114, 148, Gomory barriers, 186 Gomory, Ralph E., 186 Grabarchuk, Serhiy, 92, 131, 195 graph, 12–15. Gray code, 179, 207 greedy approach, 15–17 Greenes, C. E., 207 Gros, Lois, 180, 207 Guarini’s puzzle, 14–15, 108, 115, 195 Guarini, Paolo, 14 Hamilton circuit, 100, 205, 222 Hamilton path, 114. Hamilton, Sir William, 38 Handshaking Lemma, 141 Hess, Dick, 118 heuristic, 205 Hofstadter, Douglas, 178 Hurkens, C.A.J., 157 Hwang, F., 125 Iba, G., 221 Icosian Game, 38 incremental approach, 9, 84, 140, 141 initial condition, of recurrence relation, 26 instance simplification, 11, 252 instance, of a puzzle, 3 interview question, 17, 87, 88, 89, 122, 166, invariant, 28–31 tiling, domino graph, directed 115, 139, 175, 179, 181, 185, 191, 209, 215, 229, 240 171, 188, 195, 208 domino, 59 See See n bottom-up, 249–250 by another constant, 250 by constant factor, 250 by one, 249–250 by two, 250 by variable number, 250 index of applications, 251 index of applications, 251 index of applications, 251 index of applications Game of Life, 65–66, 215 Gardiner, A., 124 Gardner, Martin, 18, 82, 86, 89, 106, 112, factorial, 4 Feijen, W. H., 199 Fibonacci numbers, 46, 127, 214 Fibonacci, Leonardo, 82, 127, 190 Fifteen puzzle, 68 floor (mathematics), 9 Fomin, D. B., 151 Frame-Stewart algorithm, 208 Frobenius coin problem, 121 edge, of a graph, 12 Engel, Arthur, 162 enumeration method, 217–218 Eperson, D. B., 186 Eppstein D., 193 Euler circuit, 29, 30, 101, 102, 182 Euler path, 30, 102 Euler, Leonhard, 29, 30, 205 exhaustive search, 4–5, 7–8 exponential rate of growth, 5, 24, 27 dynamic programming, 20–22 Dudeney, Henry E., 14, 30, 85, 86, 112, 145, double- domino. Dijkstra, Edsger W., 199 Dirac’s theorem, 221 divide-and-conquer, 9–10 decrease-by-constant-factor, 9, 24, 250 decrease-by-one, 8–9, 249–250 degree, of a vertex, 29, 101, 102,Delannoy, 182, Henri, 222 211 Demuth, H. B., 203 digraph. decrease-and-conquer, 8–9 Index of Terms and Names 256 irsf,1,87 17, Microsoft, 138 Z., Michalewicz, 138 M., Michalewicz, 144 143, median, 44 number, McNugget 124, 111, 94, induction, mathematical 136 (game), Mastermind 143 118, 50, distance, Manhattan 150 Udi, Manber, 103 sum, magic 103–104 40, 39, 4–5, square, magic 208 160, 159, 27, Édouard, Lucas, 218 Stephen, Lucas, 195, 188, 171, 145, 111, 30, Sam, Loyd, 24 growth, of rate logarithmic 48 40, problems, pouring liquid 67 24, growth, of rate linear 87 X., S. Levmore, 199 A., Levitin, 219 K.R.M., Leino, 161 H., D. Lehmer, 161 problem, motel Lehmer’s 5 tree, a of leaf, 98 square, Latin 101 29–30, problem, Bridges Königsberg 151 D., L. Kurlandchik, 217 117, 106, Maurice, Kraitchik, 141 140, 138, A., B. Kordemsky, 238 M., Kontsevich, 198 Joseph, Konhauser, 203 179, 128, E., Donald Knuth, 127 Ron, Knott, 188 S., M. Klamkin, 231 U., Ernest Kinsey, 150 N., K. King, 238 A., Khodulev, 225 Flavius, Josephus, 67 problem, Josephus 196 R., Johnsonbaugh, 160 algorithm, Johnson-Trotter 17–20 improvement, iterative 230 172, inversion, ne fapiain,252 applications, of index 2,228 224, 211, 206, 201, 196, 192, 177, 176, 172, 170, 164, 162, 153, 145, 126, 231 229, aoafunction. pagoda 172 134–135, 47, octagon, 226 89, H., T. O’Beirne, 231 134, NP-complete, 24 algorithm, nonrecursive 6 node, nonpromising 157 D., Niederman, 222–223 111, 67, 6–8, problem, n-queens 29–30 multigraph, 87 Leo, Moser, 193 C., Moore, 205 Rémond, Pierre Montmort, 232 227, 221, 151, 137, 19–20, monovariant, 51 monomino, 219 Lloyd, W. Milligan, ucsr,97 quicksort, 135 quickhull, 109–110 queue, 24 growth, of rate quadratic 82 31, George, Pólya, 40 square, pseudo-magic 197 James, Propp, 95 Euler, Project 253 11, reduction, problem 11 presorting, 129 87, 82, 12, William, Poundstone, Petkovi´ 110 Ivar, Peterson, 229 160–161, 5, permutation, 223 E., Pauls, problems path 171 22, triangle, Pascal’s 134 problem, partition 248 28, (invariant), parity 92 Ian, Parberry, 171 158, 56, palindrome, nlsso,24–25 of, analysis ne fapitos 252 applictions, of index 100 of, ranking 230–231 of, parity 230–231 in, inversion 34 20, counting, path shortest 59 51, 50, 47, 36, optimal, 64 43, 42, 38, 36, Hamilton, 38 30, Euler, 61 crossing, dot . 207 M., c See eorecount resource 257 Index of Terms and Names backtracking See also tiling, tetromino tiling, tromino See See right, 10, 35–36, 55, 62 straight, 51 round-robin, 37, 217 single-elimination, 40, 61 tree, 106 extension of (Reve’s puzzle), 64, 207–208 restricted, 27, 52 index of applications, 252–253 decision, 89, 225–226 leaf of, 5 root of, 5 state-space, 5 balanced, 190 domino, 28, 34, 54, 60, 228–229 tetromino, 41–42 trapezoid, 54–55 tromino pruned, 6 Tower of Brahma, 27 Tower of Hanoi, 25–27, 153, 179 transform-and-conquer, 11–15 tree, 5 triangular numbers, 167, 176 Trigg, Charles, 157, 186, 188 tromino. Turing, Alan, 37–38 Tweedie, M.C.K., 110 vertex, of a graph, 12 Warnsdorff, H. C., 205 Webb, William, 204 Wegman, Mark, 176 weighing problems, 34, 43, 45, 55, 61,Winkler, 64, Peter, 67 128, 198, 227 Topswops, game of, 55–56 tournament Steinhaus, Hugo, 160, 181, 204 Stevens, B., 223 Stewart, Ian, 204 Tabari, Hasib, 190 Tait, Peter Guthrie, 65, 102, 211 Tanton, James, 125, 188, 214, 221 Tarry, Gaston, 182 telescopic series, 126 ternary numbers, 11, 12, 189, 226 tetromino. tiling state-space tree, 5–7. See also 159, 160, 175, 202, 205, 207, 208, 211, 225 presorting 33, 44 151, 160, 163, 164, 168–169, 178, 179, 182, 195–196, 206, 207, 209–211, 215, 227–228 150, 151, 154, 176, 179, 191, 197, 198, 207, 211, 224 by bubble sort, 171 by insertion sort, 171 by quicksort, 97 analysis of, 25–27 index of applications, 252–253 second-order linear, 206–207 exponential, 5, 24, 27 linear, 24, 67 logarithmic, 24 quadratic, 24 Spivak, A., 85, 111, 114, 119, 169 state-space graph, 12–14, 82, 110, 121 Slocum, J., 231 Smith-Thomas, B., 150 Sniedovich, Moshe, 87, 198 Sonneveld D., 231 sorting, 46, 52, 56, 63, 64, 126, 144. Savchev, S., 199 Savin, A. P., 215 Schweik (literary hero), 46, 126 Scorer, R. S., 153 selection problem, 144 Shasha, Dennis, 136, 209 Shashi, 23 Sillke, Torsten, 87 simplex method, 20 Singmaster, David, 93, 121, 125, 139, Robertson, Jack, 204 root, of a tree, 5 Rosen, Kenneth, 178 Rosenbaum, J., 179 Rote, Günter, 87 Roth, Ted, 208 Rubik’s Cube, 14 representation change, 11 resource count, 212–214, 236–238 river-crossing problems, 12–14, 17, 32, recursion, 8 recursive algorithm, 8, 10, 26, 97, 101, 121, recurrence relation, 26, 125, 127, 137–138, Rand, Michael, 208 rate of growth, 24