How to Build a Maze

David Matuszek Department of Computer Science 8 Ayres Hall University of Tennessee Knoxville TN 37916

Mazes are fun to solve. With a little random traditional maze. creation of this spanning tree that is imagination, mazes can be incorpor­ the tricky part of building a maze. ated into many different computer The General Approach Finally, the border of the maze is games. If you know how, it's a simple We begin with a rectangular array. broken in two places to provide a matter to use the computer to gener­ Each cell of the array is initially com­ start and a finish position. Since there ate random mazes. pletely "walled in," isolated from its is a unique path between any two A traditional maze has one starting neighbors (see figure 1). cells of the maze, there will be a point and one finishing point. In ad­ Secondly, we judiciously erase unique path from start to finish. dition, all locations inside the maze walls inside the array until we arrive Hence, start and finish can be chosen are reachable from the start, and at a structure with the following in any convenient manner, say, at there is one and only one path from property: for any two 'cells of the ar­ random locations on opposite sides of start to finish. While it is easy to place ray, there is only one path between the maze (see figure 3). doorways and barriers randomly in­ them. Thus, any cell can be reached side it maze, it is more difficult to from any cell, but only by a single Building the Spanning Tree satisfy the two latter constraints. This unique path (see figure 2). Computer­ Starting with a fully "walled-up" article describes a fairly simple science jargon refers to such a struc­ array (see figure 1), pick a single cell method that efficiently produces a ture as a spanning tree, and it is the in the array and call , this cell the

Figure' 1: The initial array from which the Figure 2: One possible spanning tree for Figure 3: The spanning tree from figure 2 maze will be constructed. the array in figure 1. with possible entry and exit points added.

190 December 1981 © BYTE Publications Inc Circle 20 on inquiry card. --+

II! I I

a b c d e

Figure 4: Initial steps involved in building a maze. The cell added at each step is marked with an asterisk. The next cell to be added to the maze will be selected from the shaded frontier cells. spanning tree. Then adds cells one at The algorithm follows: it to, and erase the appropriate bar­ a time to the spanning tree until it rier. fills the entire array. 3. Check the cells adjacent to the cell At any point during this procedure, 1. Choose any cell of the array and just added to the spanning tree. Any there will be three types of cells in the call it the spanning tree. The four cells such cells that are not part of the array: immediately adjacent to it (fewer if it spanning tree and have not previous­ is on an edge or in a corner) thus ly been marked as frontier cells must • those that are already in the span­ become frontier cells. now be marked as frontier cells. ning tree 2. Randomly choose a frontier cell 4. If any frontier cells remain, go • those that are not in the spanning and connect it to one cell of the cur­ back to step 2. tree, but are immediately adjacent rent spanning tree by erasing one bar­ 5. Choose start and finish cells. (horizontally or vertically) to some rier. If it is adjacent to more than one cell in the spanning tree (we call these cell of the spanning tree (and it could cells frontier cells) be adjac~nt to as many as four!), ran­ Figure 4 shows the first few steps in • all the other cells domly choose one of them to connect building a maze. In each case the ar­ ray is shown as it would be just before execution of step 2 of the algorithm. Note that the newly added 96K CP/M@ cell (marked by an asterisk) in figure 4e was adjacent to two cells in the (For your TRS-80* Model II) spanning tree, yet it was connected to only one of these (the one to its left) Multiple Job Executive by randomly choosing and erasing Add a whole new dimension to your one barrier. TRS-80 Model II. Let it work while you If you're mathematically inclined, . work!! it· is easy to show by induction that this process results in a-spanning tree. ATON's unique JobStream™ CP/M 2.2, along with additional RAM memory; allows you to simultaneously compile, assemble, or link in one 64K background partition 162K TPAI while you When the tree consists of a single cell, edit files, and spool to the printer, and communicate with another computer in up to four 32K there is (vacuously) only one path be­ foreground partitions 128K TPAI. As you expand memory beyond 64K, you also enter the amazing world of TrackMode BIOS™ tween any pair of cells. As each new which not only multiplies diskette speed up to five times, but also automatically performs read cell is added, it forms no new paths after write checks for the ultimate in data reliability. • Gain hard disk performance for a fraction of the cost-and no backup problems!!! between cells already on the tree • Works in 32K, add RAM memory to 256K using standard Radio Shack memory boards . (since the tree is a dead end), and • Supports two sided expansion disk drives 0.2 megabytes per diskettel. there iS,exactly one path from the new JobStream CP/M 2.2 (with Z-80** Debugger) $235 cell to any other cell (you can get out Omni Writer™ Video Text Editor $130 via only one cell, and from that cell Z-80 Debugger Source Code $ 50 there is only one path). Finally, the Package of above (a $415 value) $295 process ends when there are no more "Software with Service" Prepaid, Visa, MasterCard or COD. frontier cells (cells adjacent to the Shipping and handling extra. spanning tree but not in it), and this California residents add 6% sales tax. can happen only when all cells have CP / M ~ Digital Research. In c. OIT WT andy Corp . .. fwZilog Corp . been absorbed into the spanning tree. JobStream, TrackMode BIOS ' · ATDN IntI. 1 Omni Writer " Omnig raphics 260 Brooklyn Avenue, San Jose, CA 95128 Implementation Details (408) 286-4078 You should store in each cell of the

192 December 1981 © BYTE Publications Inc Circle 37 on inquiry card. To perform to Its fullest capabili­ UniFLEX. strucftj~d tor lorge-scale Support Software ties, your hardware demands microprocessor systems, will not Teohnlcal Systems Consultants software designed t meet the run with minimal systems and"thus offers a full line of state-of-the-art specialized require ents of has avoided design compromise. support software compatible to today's mlcroprocess,ors. State-of­ (Off-the-shelf versions and OEM FLEX and UnlFLEX, some of which the-art software from Technical licenses are available.) are: Systems Consultants ~ eeps pace • native C and Pascal compliers with the rapid advancements In The FLEX TM OperaHng System for advanced programming computer technology so your FLEX. a powerful. easy-to-use • extended BASIC for business hardware can live up to Its full operating system designed for and educational applications potential. Our comptete line of the 6800 and 6809 microproces­ • text editing and processing state-of-the-art software Includes: sors, Includes: software • dynamic fllespace allocation • sort/merge package for busi­ The UnlFLEXTMOperaHng System • random flies ness applloatlons UnlFLEX, a true multl-u'ser, multi­ • batch job entry • variety of absolute and relocat­ tasking system for the 6809 and • automatic space compression able assemblers 68000 mlcroprocesso s. supports • English error messages • debug and diagnostic such features as: • user environment control packages • hierarchical file sys ms • disk resident commands · . . and more. Write or call today • device Independent 1/0 • flexible device 1/0 for our broohures describing • four Gigabyte disk capacities • printer spooling our oomplete product line. • full file protection Plus. FLEX can accommodate • Inter-task communication via hard disks as well as floppies. The pipes System Is available off-the-shelf :1 = i i i ~ I ' • 1/0 redirection for a variety of systems and In a , '-< - • task swapping field-adaptable version. epEM ~~§i; • full random-access flies lIoenses available.) Box 2570,1208 Kent Avenue • comprehensive shell comma d West Lafayette. Indiana 47906 language FLEX and UnlFLEX are trademarks of (317) 463-2502 Telex: 27·6143 Technical Systems Consultants. Inc. sc ulpture by Joann Chaney Circle 303 on Inquiry card

array a number indicating: 1 . Introdudng whether it is in the spanning tree, in w the frontier, or in neither; and 2. if it Pascal is in the spanning tree, which of the Sourcebooks cell's barriers have been erased. One from the NATI Pascal Software library possibility is to use-1 for frontier I PHJCEIXJRE wand input· cells, positive numbers for cells, I BEnIN {wand-. positive numbers for cells in the span­ I - ning tree, and 0 for all other cells. Complete I Ann~tated any cell of the spanning tree is open I Program Usdngs to at least one other cell, I suggest the I Cross Refe,rences and following encoding: start with 0 in Block Summaries each cell, add 1 if the barrier on the Block Indices by Page This new library of UCSD Pascal' compatible pro­ 5a right is erased; add 2 if the barrier grams provides practical applications and system below is erased; add 4 if the barrier augmentations available nowhere else. Each Pascal on the left is erased, and add 8 if the Sourcebook 1M is a treasure trove of Ideas and pro­ ven program techniques, These Pascal programs will barrier above is erased. The result run on every major personal computer system cur­ will be a number from 1 to 15 that rently manufactured which has the UCSD p-System' installed. II II II II specifies exactly which combination Pascal Sourcebooks TM contain completely com­ mented and annotated source listings and machine of barriers has been erased. (Decod­ readable bar code texts .... of well designed. clearly ing this number shouldn't be too hard written UCSD Pascal' programs. Use the programs if you work with binary numbers.) "as is " , or modify and customize them to your own II II II II personal tastes . Either way. yougaln1a practical Note that when you erase a barrier working library available nowhere else, between two cells you will have to File SYltem: Interrogate dlreclorles Irom appllcallon programs in order to select exlsllng Illes or create new Illes Interactively .. add the appropriate numbers to each FS ,OI Pllell Sourcebook TM i lane·· ·· ...... 569.95 II II II II FS,02 Pllell Sourcebook™ and Apple Pelcll" medii .. 599,95 of them. Increm.nlll 81ckup SYltem: Use these 'dally ;ltuals to save The minor exception mentioned recenlly used flies to prevent loss 01 Iloppy or hard disk data. 18S.01 Pllell Sourcebook™ Ilane ...... : ..... 569.95 above is the initial cell of the span­ IBS.02 Pelell Sourcebook TM .nd Apple Pelell" medII . 599,95 II II II II Report Genar.lor: Use this report lormattlng program to create ning tree, immediately after step 1 of prolesslonal word processing quality documentallon with the it UCSD Pascal' system's Screen Editor. Uses Diablo, NEe , Rlcoh . the algorithm (see figure 4a). Since Ah.arn&Soper , etc . printers with Diablo 1620 compatible serial is the first, it is not yet open to any interface. ' 5b RGI.Ol Pllell Soureibook™ .ton ...... , .... 579.95 other cell. Give it the value 16 (or RGf.02 Pllell Sourc.book TM & Apple ~1Ie11" medII . . 5109,95 Tel.phon. Utltltles: Use these Hayes Smartmodem'" programs 100, or 1984, if you prefer) so that it to dial originate or answer mode data calls. Save session images will be positive, and subtract this on disk. Transler Illes to the line. Use the autodialer lor voice calls . number out again in step 5. TU,OI Pelell Sourc.book™ Itone ...... $59.95 lU.D2 P.,ell Sourcebook TM .n~ Appl. Pllell" m.dll . 589.95 Now that the array representation Graphic Apptlclllonl-t:Practical examples 01 Pascal programs driving appllcallon oriented graphics: examples of hydro power has been settled, let's discuss efficient prollles, spherical lens ray tracing, sun·earth·moon orbllal model. implementation of the algorithm. In numerical integration. etc. GAf.Ol Pliell Sourc.book™ .Ion ...... SI9.95 step 2 a frontier cell was randomly GAf.02 Pllell Sourc.book TM .nd Appl. Pelell" medII . S49.95 Typewriter Simutators: Use a word processing quality printer with chosen. To prevent bumbling around your terminal as an eclectic electric typewriter. Automatic in the array, you must keep a list of address accumulation. envelope addressing . line by line correc· tion. Uses Diablo. NEG. Ricoh . AhBarn&Soper . etc. printers with those cells. This can be simply ac­ Diablo t 620 compatible serial interface. I T51.01 Pascal Sourcebook TM atone...... $49.95 complished by storing the indices of TSI.02 Pascal Sourcebook TM and Apple Pascal" media . $79 ,95 UCSD Pllcallnd UCSD p·Syslllm are trldllmlrk~ of the Reglnts the n cells of the frontier (each of 01 the Sttt. ot Ct,"orn~ •• Apple Pascal i. I . trademark 01 thll Applll Computer Company which is specified by a row number ••• Smartmodem I•• tradlmark of HIYes -Mlcrocomputllr Product • •••• All Pascal Sourcebook. TM Include NATI Tllxt Formal™ bar Codl and a column number) in the first n Images of comprllllld machlnll rtldabll PISClllingulge .ource texts . Bar code rildllrs and bootstrlp softwlre art availlible for locations of two arrays, R (row num­ Apple PISCII mlchlnes . bers) and C (column numbers). A De81er Inquiries Invited 5c FREE BONUS! With each order. we'll send customers a per· frontier cell can be quickly chosen by sonal copy of the booklet " Alternative Software Delivery Media " randomly choosing a k less than or describing our NATI Text Format™ printed bar code technology Figure 5: For an m by n maze to be dis­ equal to n, and using the cell whose MIiit_ NORTH AMERICAN played on a computer graphics system, a TECHNOLOGY, INC• indices are given by R(k), C(k). ... Strand Building resolution of at least 2m + 1 by 2n + 1 •••,,~ , , 174 Concord 51. Since the order of the n frontier cell must be available. The 4- by 4-maze array Peterborough, NH 03458 locations in arrays Rand C is not im­ (603) 924·7136 of figure 5a requires a graphics array of 9 by 9. The initial cells of the 4 by 4 array portant, the following code suffices to Order your Pascal Source books TM and media are shown displayed using the 9 by 9 remove the chosen cell k: copies now . Call our 24 hour credit card phone order service with your Master Card , resolution in figure 5b. The finished maze, R(k) = R(n) or Visa billing Inlormatlon : with openings between the cells where C(k) = C(n) 800-854-0561 operator 860 paths exist, is shown in figure 5c. n = n-1 (or in CalHornia, 800-432-7257 operator 860)

194 Decem~r 1981 © BYTE Publications Inc hard •

MICRO PRO MORE GREAT APPLE GAMES APPLE BUSINESS SOFTWARE

APPLE CP/M® COMPUTER QUARTERBACK . . . . 32.95 MAGIC WINDOW ...... 79.00 THE WARP FACTOR ...... 32.95 DB MASTER (NEW) .. .179.00 WORD STAR" ...... 259.00 CARTELSANDCUITHROATS...... 32.95 PFS: PERSONAL FILING SYS. . . .. 84.00 SUPER SORT' ...... 145.00 TORPEDO FIRE ...... • . . . • . •... 49.95 PFS: REPORT...... • . • . • . • . .. . S4.00 MAIL MERGER ' .. .. 90.00 THE SHAITERED ALLI ANCE . . . 49.95 Z·TERM· ...... 79.95 DATA STAR' ...... 215.00 COM PUTER BASEBALL . . • . • . • . • . • . ' . 32.95 ASCII EXPRESS ...... •.•...... 63.95 SPELLSTAR · . . 195.00 POOL 1.5 ...... •. • ...... 29.95 HAYDEN APPLESOFT COM PiLER .. . .• ...... 149.00 ULTIMA . . .. . 33.95 EASY WRITER·PRO ...... • . • ... . 199.00 8-100 CP/M® RASTER BLASTER ...... 24 .95 FLIGHT SIMULATOR ...... 27 .95 ' S·100 SOFTWARE WORDSTAR ...... 310.00 INTERNATIONAL GRAND PRI X. . . 25.95 SUPER SORT .195.00 COSMO MISSION ... 24.95 MAIL MERGER ...... 110.00 SARGON II ...... • . • . • ...... 2S.95 d BASE II . ... 599.00 DATA STAR ...... 245.00 SHUFFLE BOARD ...... • . • . • . •. • . • . •.... 29.95 SUPER CALC ...... 249 .00 SPELL STAR ...... 195.00 MAGIC WAND .. 279.00 SPELLGUARD . .. 239.00 MICROSOFT PICKLES AND TROUT CPIM ® MOD. II TRS·SO .. 175.00 BRODERBUND APPLE EDU·WARE TAWALA'S LAST REDOUBT ...... 24 .95 FORTRAN" . . .. . 165.00 BASIC COMPILER' ...... • . . 315.00 GALAXY WARS ...... • . ... 20.95 PERCEPTION PKG ...... 19.95 ALIEN RAIN (AKA GALAXIAN) ...... 20.95 COBOL' . . ... 595.00 APPLE SOFT COMPILER . . 159.00 COMPU·READ ...... 24.95 SNOGGLE (REQ . JOYSTICK) . . . 27 .95 STORY TELLER ...... •..... 1S.95 ALIEN TYPHOON ...... 20.95 Z·SO SOFTCARD ...... • . . . 299 .00 RAMCARD ... 159.00 COMPU·MATH: ARITHMETIC . ... .• . • ...... 39.95 APPL E PANIC ...... •.. .. . 24 .95 COMPU·MATH: FRACTIONS ...... 34.95 SPACE WARRIOR . . . 20.95 TYPING TUTOR ...... • . • ...... 17.95 OLYMPIC DECATHLON .. • . • . • • . .. • . • . ... . 24 .95 COMPU·MATH: DECiMALS ...... • .... 34 .95 . COMPU·SPELL (REQ. DATA DISK) . . . .. 24.95 AUTOMATED COM PU SPELL DATA DISKS 1·4,ea. . .. 17.95 SIMULATIONS 8-100 CP/M® BASIC so ...... • . ....•. • . •.. .. . 299.00 TRS·80 GAMES IN VASION ORION . . . . . 20.95 BASIC COMPILER ...... 319.00 . . 32.95 FORTRAN SO ...... 399.00 .. 34.95 TU ES. MORNING QUARTERBACK . . . . 25.95 COBOLBO ...... 599.00 . . . .• . • . . .. 34.95 CRU SH, CRUMBLE AND CHOMP . . . . . 24.95 STAR WARRIOR...... • . • ...... 34 .95 THE DRAG ON'S EYE . .. .. 20.95 PEACHTREE ...... 24.95 CRUSH , CRUMBLE AND CHOMP. . . 24.95 MUSE SOFTWARE APPLE CP/M ® INVADERS FROM SPACE . . . . 17.95 PINBALL ...... •.•.... 17.95 GENERAL LEDGER ...... 219.00 STAR TREK 3.5 ...... 17.95 ROBOT WARS ...... " " " ...... " ,, 32.95 ACCT. RECEIVABLE ...... 219.00 MISSILE AITACK ...... 1B.95 THREE MILE ISLA ND ...... 32 .95 ACCT. PAYABLE .. .•.• . • . • .... 219.00 STAR FIGHTER ...... 24.95 A. B.M ...... " .. " ...... 20.95 PAYROLL ...... " .... 219.00 GLOBAL WAR ...... • . • ...... 20.95 IN VENTORY...... •...... 219.00 ' REQUIRES Z·SO SOFTCARD CAS1L£ 'NOLFENS11 EN ...... 24.95 SUPER TE XT II ...... 129.00 8-100 CP/M® ON·LlNE SYSTEMS GENERAL LEDGER ...... 595.00 ACCT. RECEIVABLE ...... 595.00 IF YOU DON'T SEE IT, MYSTERY HOUSE . . 20 .95 ACCT. PAYABLE ...... 595.00 WIZZARD AND PR IN CES...... 29.95 CALL US. WE HAVE ALL PAYROLL ...... 595.00 H/R FOOTBALL ...... 32.95 IN VENTORY ...... • . . . • . . • . • . . . 595.00 THE LATEST SOFTWARE. H/R CRIBBAGE ...... •. • . •...... 20.95 PROPERTY MGMT...... • . • ...... 799.00 MISSLE DEFENSE ...... 25.95 CPA CLIENT WRITE·UP . . . 799.00 CRAN STON MANOR ...... • . • . . . . . • . . .. . 29.95 SA BOTAGE ...... 20.95 GOBBLERS ...... 20.95 son PORN AD VENTURE . . . • . . . . . • . . . . . 24.95 PEGASUS II ...... • .•... . 25.95 EXPEDITER ...... 73.95 We built a reputation on our prices and your satisfaction. PERSONALSOFTWARE We guarantee everything we sell for 30 days. If anylh ing DESKTOP PLAN II . . .. . 159.00 is wrong . just re turn th e item and we'lI make it righ t. CCA DATA MGT. SYS1EM .S9.00 And. of cour se. we'lI pay the sh ipping charges. VISIPLOT . . 159.00 We accept Visa and Master Card on all ord ers. COD VISITRENDIVISIPLOT . . .. . 199.00 VISIDEX...... 159.00 acc epted up to $300.00 . VISITERM ...... 129.00 Pl ease add $2 .00 for slandard UPS shipping and VI SICALC 3.3 ...... 159.00 hand I ing on orders under 50 pounds. deli vered in th e CHECKER KING . . 21 .95 GAMMON GAMBLER ...... 21.95 contin enta l U.S. Call us for shipp ing charges on ilems BRIDGE PARTNER ...... • . . 21 .95 that wei gh more than 50 pounds. Foreign. FPOa nd APO MONIY PLA YS MONOPOLY ...... • ...... 29.95 order s plea se add 15% for shipp ing . Cal iforni a res­ ZORK ...... 32.95 ident s add 6% sales tax . MONTY PLAYS SCRABBLE ...... 34.95 SIRIUS SOFTWARE

PHANTOMS FIVE . ... •• .• ...... 24.95 SPACE EG GS ...... • . . .. 24.95 AUTOBAHN ...... • ...... 24 .95 PULSAR II ...... • . . • . . ... 24.95 GAMMA GOBLINS ...... • . . • . . ... 24.95 GORGON ...... 32.95 31245 La 8aya Drive, Westlake Village, California 91362 SNEAKERS ...... 24.95 The pri ces quoted are onl y val id for stoc k on hand and all pri ces are subjecllo change without notice. EPOCK ...... 29 .95 COPS AND ROBBERS . . .. • ...... 29.95 CP/M® is a reg istered trademark of Digital Research. Circle 14 on inquiry card. 6a XXXXXXXXX 6b XXXXXXXXXXXXXXXXXX When this frontier cell is added to X X XX XX the spanning tree, some of the cells XXX X XXX XXXXXX xX' XXXXXX adjacent to it (those having a zero X X X X XX XX XX XX value) become new frontier cells, X X X X X XX XX XX XX XX and their locations must be inserted X X X X XX XX XX XX into the Rand C arrays. Adjacent X XXX X X XX XXXXXX XX XX cells with value -1 are already fron­ X X XX XX tier c~lls and already have their loca­ XXXXXXXXX XXXXXXXXXXXXXXXXXX tions recorded in the Rand C arrays; they must not be inserted again. Figure 6: The maze of figure 5 as it might appear as printed output, with each maze­ Finally, how large should arrays R array element represented by space characters or X characters. One space or X is used in and C be? For an m by n array, 6a; two spaces or Xs are used in 6b. analysis shows that in the worst case ------1 (2/3) mn locations will be required, but practical experience shows that 3(m + n} is almost always enough. However, if you use the latter figure there is a slight probability that the program will fail.

Concluding Remarks While we have discussed building a maze, nothing has been said regard­ ing how to display it. That depends entirely on your particular-hardware and software; the answers are dif­ ferent for the display screen of a Commodore PET than for that of an Apple II, and different again for a character printer. To display a maze on a screen with graphics capabilities, the following scheme is appropriate. For an m by n maze, you need to be able to display at least 2m + 1 points vertically and 2n + 1 points horizontally-the "cells" will be those points at the in­ tersection of even-numbered rows with even-numbered columns (see figures Sa through 5c). Maze building on the screen proceeds exactly as in figures 1 through 3, except that the walls are necessarily thicker. To print a maze out, the same gen­ eral scheme is used with, say, "X" characters for walls and blanks for paths (see figure 6). Of course, you can't erase an X once it is printed, so it will be necessary to build the entire maze internally before printing it. Then you can decipher and print the maze one row at a time. As a final note, if you are an afi­ cionado of hexagonal grids, the maze algorithm is easily modified for other than rectangular grids. Implementa­ tion may be a bit messy-but then, implementation is always messy .•

196 December 1981 © BYTE Publications Inc Circle 447 on Inquiry card.