home *** CD-ROM | disk | FTP | other *** search
/ Collection of Hack-Phreak Scene Programs / cleanhpvac.zip / cleanhpvac / FAQSYS18.ZIP / FAQS.DAT / MAZE-FAQ < prev    next >
Text File  |  1994-10-06  |  25KB  |  896 lines

  1. ========================================
  2. Maze FAQ
  3. ========================================
  4.  
  5. Sorry this is NOT an organized FAQ it's still useful though
  6. ------------------------------------------------------------
  7.  
  8. Oh, you're really going to love this one.  It's an obfuscated C code
  9. mazegenerator.  Fun fun fun.  Well, if you can figure it out, there's
  10. youralgorithm.  Fun fun fun.
  11.  
  12. char*M,A,Z,E=40,J[40],T[40];main(C){for(*J=A=scanf(M="%d",&C);
  13. --            E;             J[              E]             =T
  14. [E   ]=  E)   printf("._");  for(;(A-=Z=!Z)  ||  (printf("\n|"
  15. )    ,   A    =              39              ,C             --
  16. )    ;   Z    ||    printf   (M   ))M[Z]=Z[A-(E   =A[J-Z])&&!C
  17. &    A   ==             T[                                  A]
  18. |6<<11<rand()||!C&!Z?J[T[E]=T[A]]=E,J[T[A]=A-Z]=A,"_.":" |"];}
  19.  
  20. Pretty cute, no?
  21.  
  22. --
  23. Brad Threatt | MISSING! Single white male Jesus look-alike in blue
  24.        | Members Only jacket.  Answers to the name 'Dave Gillespie'.
  25. Safe sex is  | Last seen with roller-skating couple in Pasadena.
  26. for wimps.   | If found, please return to the cs10 lab immediately.
  27. ========================================
  28.  
  29.  
  30. In <1992Mar5.210706.24104@wpi.WPI.EDU> rcarter@wpi.WPI.EDU (Randolph
  31. Carter (nee. Joseph H. Allen)) writes:
  32.  
  33.  
  34. >>char*M,A,Z,E=40,J[40],T[40];main(C){for(*J=A=scanf(M="%d",&C);
  35. >>--            E;             J[              E]             =T
  36. >>[E   ]=  E)   printf("._");  for(;(A-=Z=!Z)  ||  (printf("\n|"
  37. >>)    ,   A    =              39              ,C             --
  38. >>)    ;   Z    ||    printf   (M   ))M[Z]=Z[A-(E   =A[J-Z])&&!C
  39. >>&    A   ==             T[                                  A]
  40. >>|6<<11<rand()||!C&!Z?J[T[E]=T[A]]=E,J[T[A]=A-Z]=A,"_.":" |"];}
  41.       ^^
  42. This should be 28 if rand() returns a 32-bit quantity.
  43.  
  44. >>Pretty cute, no?
  45.  
  46. >No style at all.... :-)
  47.  
  48. ========================================
  49.  
  50. >--
  51. >/*  rcarter@wpi.wpi.edu */      /* Amazing */             /* Joseph H.
  52. Allen */
  53. >int
  54. a[1817];main(z,p,q,r){for(p=80;q+p-80;p-=2*a[p])for(z=9;z--;)q=3&(r=time(0)
  55. >+r*57)/7,q=q?q-1?q-2?1-p%79?-1:0:p%79-77?1:0:p<1659?79:0:p>158?-79:0,q?!a[p+q*
  56. 2
  57. >]?a[p+=a[p+=q]=q]=q:0:0;for(;q++-1817;)printf(q%79?"%c":"%c\n","
  58. #"[!a[q-1]]);}
  59.  
  60. Well, it doesn't produce a maze, but try this one...
  61.  
  62. int a=10000,b,c=2800,d,e,f[2801],g;main(){for(;b-c;)f[b++]=a/5;for(;d=0,g=c*2;c
  63. -=14,printf("%.4d",e+d/a),e=d%a)for(b=c;d+=f[b]*a,f[b]=d%--g,d/=g--,--b;d*=b);}
  64. (I disclaim any credit for this!)
  65. --
  66. John Brownie
  67. School of Mathematics and Statistics
  68. University of Sydney
  69. Internet: jhb@maths.su.oz.au
  70.  
  71.  
  72.  
  73. ========================================
  74.  
  75. Excerpts from programming: 6-Mar-92 Re: Algorithm to create a m.. Mark
  76. Howell@movies.enet. (5723)
  77.  
  78.  
  79. Here's the single level maze algorithm, solver and printer.
  80.  
  81. /*
  82.  * MazeGen.c -- Mark Howell -- 8 May 1991
  83.  *
  84.  * Usage: MazeGen [width [height [seed]]]
  85.  */
  86. #include <stdio.h>
  87. #include <stdlib.h>
  88. #include <time.h>
  89.  
  90. #define WIDTH 39
  91. #define HEIGHT 11
  92.  
  93. #define UP 0
  94. #define RIGHT 1
  95. #define DOWN 2
  96. #define LEFT 3
  97. #ifdef TRUE
  98. #undef TRUE
  99. #endif /* TRUE */
  100.  
  101. #define TRUE 1
  102.  
  103. #define cell_empty(a) (!(a)->up && !(a)->right && !(a)->down && !(a)->left)
  104.  
  105. typedef struct {
  106.     unsigned int up      : 1;
  107.     unsigned int right   : 1;
  108.     unsigned int down    : 1;
  109.     unsigned int left    : 1;
  110.     unsigned int path    : 1;
  111.     unsigned int visited : 1;
  112. } cell_t;
  113. typedef cell_t *maze_t;
  114.  
  115. void CreateMaze (maze_t maze, int width, int height);
  116. void SolveMaze (maze_t maze, int width, int height);
  117. void PrintMaze (maze_t maze, int width, int height);
  118.  
  119. int main (int argc, char *argv [])
  120. {
  121.     int width = WIDTH;
  122.     int height = HEIGHT;
  123.     maze_t maze;
  124.  
  125.     if (argc >= 2)
  126.         width = atoi (argv [1]);
  127.  
  128.     if (argc >= 3)
  129.         height = atoi (argv [2]);
  130.  
  131.     if (argc >= 4)
  132.         srand (atoi (argv [3]));
  133.     else
  134.         srand ((int) time ((time_t *) NULL));
  135.  
  136.     if (width <= 0 || height <= 0) {
  137.         (void) fprintf (stderr, "Illegal width or height value!\n");
  138.         exit (EXIT_FAILURE);
  139.     }
  140.     maze = (maze_t) calloc (width * height, sizeof (cell_t));
  141.     if (maze == NULL) {
  142.         (void) fprintf (stderr, "Cannot allocate memory!\n");
  143.         exit (EXIT_FAILURE);
  144.     }
  145.     CreateMaze (maze, width, height);
  146.  
  147.     PrintMaze (maze, width, height);
  148.  
  149.     (void) putchar ('\n');
  150.  
  151.     SolveMaze (maze, width, height);
  152.  
  153.     PrintMaze (maze, width, height);
  154.  
  155.     free (maze);
  156.     exit (EXIT_SUCCESS);
  157.  
  158.     return (0);
  159.  
  160. }/* main */
  161.  
  162.  
  163. void CreateMaze (maze_t maze, int width, int height)
  164. {
  165.     maze_t mp, maze_top;
  166.     char paths [4];
  167.     int visits, directions;
  168.  
  169.     visits = width * height - 1;
  170.     mp = maze;
  171.     maze_top = mp + (width * height) - 1;
  172.  
  173.     while (visits) {
  174.         directions = 0;
  175.  
  176.         if ((mp - width) >= maze && cell_empty (mp - width))
  177.             paths [directions++] = UP;
  178.         if (mp < maze_top && ((mp - maze + 1) % width) && cell_empty (mp + 1))
  179.             paths [directions++] = RIGHT;
  180.         if ((mp + width) <= maze_top && cell_empty (mp + width))
  181.             paths [directions++] = DOWN;
  182.         if (mp > maze && ((mp - maze) % width) && cell_empty (mp - 1))
  183.             paths [directions++] = LEFT;
  184.  
  185.         if (directions) {
  186.             visits--;
  187.             directions = ((unsigned) rand () % directions);
  188.  
  189.             switch (paths [directions]) {
  190.                 case UP:
  191.                     mp->up = TRUE;
  192.                     (mp -= width)->down = TRUE;
  193.                     break;
  194.                 case RIGHT:
  195.                     mp->right = TRUE;
  196.                     (++mp)->left = TRUE;
  197.                     break;
  198.                 case DOWN:
  199.                     mp->down = TRUE;
  200.                     (mp += width)->up = TRUE;
  201.                     break;
  202.                 case LEFT:
  203.                     mp->left = TRUE;
  204.                     (--mp)->right = TRUE;
  205.                     break;
  206.                 default:
  207.                     break;
  208.             }
  209.         } else {
  210.             do {
  211.                 if (++mp > maze_top)
  212.                     mp = maze;
  213.             } while (cell_empty (mp));
  214.         }
  215.     }
  216. }/* CreateMaze */
  217.  
  218.  
  219. void SolveMaze (maze_t maze, int width, int height)
  220. {
  221.     maze_t *stack, mp = maze;
  222.     int sp = 0;
  223.  
  224.     stack = (maze_t *) calloc (width * height, sizeof (maze_t));
  225.     if (stack == NULL) {
  226.         (void) fprintf (stderr, "Cannot allocate memory!\n");
  227.         exit (EXIT_FAILURE);
  228.     }
  229.     (stack [sp++] = mp)->visited = TRUE;
  230.  
  231.     while (mp != (maze + (width * height) - 1)) {
  232.  
  233.         if (mp->up && !(mp - width)->visited)
  234.             stack [sp++] = mp - width;
  235.         if (mp->right && !(mp + 1)->visited)
  236.             stack [sp++] = mp + 1;
  237.         if (mp->down && !(mp + width)->visited)
  238.             stack [sp++] = mp + width;
  239.         if (mp->left && !(mp - 1)->visited)
  240.             stack [sp++] = mp - 1;
  241.  
  242.         if (stack [sp - 1] == mp)
  243.             --sp;
  244.  
  245.         (mp = stack [sp - 1])->visited = TRUE;
  246.     }
  247.     while (sp--)
  248.         if (stack [sp]->visited)
  249.             stack [sp]->path = TRUE;
  250.  
  251.     free (stack);
  252.  
  253. }/* SolveMaze */
  254.  
  255.  
  256. void PrintMaze (maze_t maze, int width, int height)
  257. {
  258.     int w, h;
  259.     char *line, *lp;
  260.  
  261.     line = (char *) calloc ((width + 1) * 2, sizeof (char));
  262.     if (line == NULL) {
  263.         (void) fprintf (stderr, "Cannot allocate memory!\n");
  264.         exit (EXIT_FAILURE);
  265.     }
  266.     maze->up = TRUE;
  267.     (maze + (width * height) - 1)->down = TRUE;
  268.  
  269.     for (lp = line, w = 0; w < width; w++) {
  270.         *lp++ = '+';
  271.         if ((maze + w)->up)
  272.             *lp++ = ((maze + w)->path) ? '.' : ' ';
  273.         else
  274.             *lp++ = '-';
  275.     }
  276.     *lp++ = '+';
  277.     (void) puts (line);
  278.     for (h = 0; h < height; h++) {
  279.         for (lp = line, w = 0; w < width; w++) {
  280.             if ((maze + w)->left)
  281.                 *lp++ = ((maze + w)->path && (maze + w - 1)->path) ? '.' : ' ';
  282.             else
  283.                 *lp++ = '|';
  284.             *lp++ = ((maze + w)->path) ? '.' : ' ';
  285.         }
  286.         *lp++ = '|';
  287.         (void) puts (line);
  288.         for (lp = line, w = 0; w < width; w++) {
  289.             *lp++ = '+';
  290.             if ((maze + w)->down)
  291.                 *lp++ = ((maze + w)->path && (h == height - 1 ||
  292.                          (maze + w + width)->path)) ? '.' : ' ';
  293.             else
  294.  
  295.                 *lp++ = '-';
  296.         }
  297.         *lp++ = '+';
  298.         (void) puts (line);
  299.         maze += width;
  300.     }
  301.     free (line);
  302.  
  303. }/* PrintMaze */
  304.  
  305.  
  306.  
  307. ========================================
  308.  
  309.  
  310. Excerpts from programming: 6-Mar-92 Re: Algorithm to create a m.. "Jon
  311. C. R. Bennett"@andr (4255)
  312.  
  313.  
  314. gillies@m.cs.uiuc.edu (Don Gillies) writes:
  315. > grid.  Mark each square in the grid with a unique number.  Make a list
  316.  
  317. what you want to do is make each grid in the maze into a set.
  318.  
  319. >
  320. >     rooms = n*n         /* each spot in the grid is a unique room */
  321. >
  322. >     repeat
  323. >         pick a random wall without replacement.
  324. >         if the numbers X and Y in the grid on both sides of the wall
  325. >             are different --
  326. >                 delete the wall and use a recursive depth
  327. >                 first search or brute-force loop to replace
  328. >                 all Y in the grid with X's.
  329.         what you do here is instead
  330.         pick a wall
  331.         if the rooms on either side of the wall belong to differnent sets
  332.                delete the wall
  333.                union the two sets together.
  334.  
  335. the rest is the same
  336.  
  337.  
  338. the brute force solution runs in O(n^2) this runs in O(n) (where n is the
  339. number of grids) so if you had a 100 x 100 maze, this method takes 10,000
  340. time steps, the brute force could take as many as 100,000,000 steps.
  341.  
  342. jon
  343.  
  344. p.s. below you will find some code to generate a maze this way
  345.  
  346.  
  347. ---------------------------------------------------
  348. /* maze.c   a maze generator
  349.    Jon Bennett
  350.         jcrb@cs.cmu.edu
  351.    */
  352.  
  353. /* the maze is generated by making a list of all the internal hedges
  354.    and randomizing it, then going lineraly through the list, we take a
  355.    hedge and se if the maze squares adjacent to it are already connected
  356.    (with find) is not the we connect them (with link), this prevents us
  357.    from creating a maze with a cycle because we will not link two maze
  358.    squares that are already connect by some path */
  359. #include <stdio.h>
  360.  
  361. #define DOWN 1
  362. #define RIGHT 2
  363.  
  364. struct maze_loc{
  365.     int rank;
  366.     int x,y;
  367.     struct maze_loc *ptr;
  368. };
  369. struct hedge_loc{
  370.     int x,y,pos,on;
  371. };
  372.  
  373. struct maze_loc *maze;
  374. struct hedge_loc *hedge;
  375. struct hedge_loc **hedge_list;
  376.  
  377. void link(a,b)
  378.  struct maze_loc *a,*b;
  379. {
  380.     if(a->rank == b->rank){
  381.         a->ptr=b;
  382.         b->rank++;
  383.         return;
  384.     }
  385.     if(a->rank > b->rank){
  386.         b->ptr=a;
  387.         return;
  388.     }
  389.     a->ptr=b;
  390. }
  391. struct maze_loc *find(a)
  392.  struct maze_loc *a;
  393. {
  394.     if(a != a->ptr){
  395.         a->ptr = find(a->ptr);
  396.     }
  397.     return a->ptr;
  398. }
  399.  
  400. main(argc,argv)
  401.  int argc;
  402.  char **argv;
  403. {
  404.     int x,y,i,j,k,l,tmp;
  405.     struct maze_loc *a,*b;
  406.     struct hedge_loc *htmp;
  407.  
  408.     if(argc!=3) exit(1);
  409.  
  410.     srandom(time(0));
  411.     x=atoi(argv[1]);
  412.     y=atoi(argv[2]);
  413.  
  414.     /*malloc the maze and hedges */
  415.     maze=(struct maze_loc *)malloc(sizeof(struct maze_loc)*x*y);
  416.     hedge=(struct hedge_loc *)malloc(sizeof(struct
  417. hedge_loc)*((x*(y-1))+((x-1)*y)));
  418.     hedge_list=(struct hedge_loc **)malloc(sizeof(struct hedge_loc
  419. *)*((x*(y-1))+((x-1)*y)));
  420.  
  421.     /*init maze*/
  422.  
  423.     for(j=0;j<y;j++){
  424.         for(i=0;i<x;i++){
  425.             maze[x*j+i].x = i;
  426.             maze[x*j+i].y = j;
  427.             maze[x*j+i].ptr = &maze[x*j+i];
  428.             maze[x*j+i].rank=0;
  429.         }
  430.     }
  431.  
  432.     /*init hedges*/
  433.     for(j=0;j<(y-1);j++){
  434.         for(i=0;i<x;i++){
  435.             hedge[x*j+i].x = i;
  436.             hedge[x*j+i].y = j;
  437.             hedge[x*j+i].pos=DOWN;
  438.             hedge[x*j+i].on=1;
  439.             hedge_list[x*j+i]= &hedge[x*j+i];
  440.         }
  441.     }
  442.     k=x*(y-1);
  443.  
  444.     for(j=0;j<y;j++){
  445.         for(i=0;i<(x-1);i++){
  446.             hedge[k+(x-1)*j+i].x = i;
  447.             hedge[k+(x-1)*j+i].y = j;
  448.             hedge[k+(x-1)*j+i].pos=RIGHT;
  449.             hedge[k+(x-1)*j+i].on=1;
  450.             hedge_list[k+(x-1)*j+i]= &hedge[k+(x-1)*j+i];
  451.         }
  452.     }
  453.  
  454.     k=(x*(y-1))+((x-1)*y);
  455.  
  456.     /*randomize hedges*/
  457.     for(i=(k-1);i>0;i--){
  458.         htmp=hedge_list[i];
  459.         j=random()%i;
  460.         hedge_list[i]=hedge_list[j];
  461.         hedge_list[j]=htmp;
  462.     }
  463.     fflush(stdout);
  464.  
  465.     l=k;
  466.  
  467.     /*create maze*/
  468.     for(i=0;i<l;i++){
  469.         j=hedge_list[i]->x;
  470.         k=hedge_list[i]->y;
  471.         a=find(&maze[x*k+j]);
  472.         if(hedge_list[i]->pos==DOWN){
  473.             b=find(&maze[x*(k+1)+j]);
  474.         } else {
  475.             b=find(&maze[x*k+j+1]);
  476.         }
  477.         if(a!=b){
  478.             link(a,b);
  479.             hedge_list[i]->on=0;
  480.         }
  481.     }
  482.  
  483.     printf("+");
  484.     for(i=0;i<x;i++){
  485.         printf("-+");
  486.     }
  487.     printf("\n");
  488.  
  489.     l=x*(y-1);
  490.  
  491.     for(j=0;j<y;j++){
  492.         printf("|");
  493.         for(i=0;i<(x-1);i++){
  494.             if(hedge[l+(x-1)*j+i].on){
  495.                printf(" |");
  496.             } else {
  497.                printf("  ");
  498.             }
  499.         }
  500.         printf(" |\n|");
  501.         if(j<(y-1)){
  502.             for(i=0;i<x;i++){
  503.                if(hedge[j*x+i].on){
  504.                    printf("--");
  505.                } else {
  506.                    printf(" -");
  507.                }
  508.             }
  509.             printf("\n");
  510.         }
  511.  
  512.     }
  513.  
  514.     for(i=0;i<x;i++){
  515.         printf("-+");
  516.     }
  517.     printf("\n");
  518.  
  519. }
  520. ========================================
  521.  
  522.  
  523.  
  524. Excerpts from programming: 9-Mar-92 Re: Algorithm to create a m.. Don
  525. Gillies@m.cs.uiuc.ed (609)
  526.  
  527. Here is another algorithm I just thought of -- how well does it work?
  528.  
  529. 1.  create a GRAPH with n*n nodes.
  530. 2.  for each node in the graph create 4 edges, linking it to the
  531.     node in the north, south, east, and west direction.
  532. 3.  Assign a random weight to every edge.
  533. 4.  Run a minimum spanning tree algorithm (take your choice
  534.     from any algorithms textbook) to produce a graph.  A minimum
  535.     spanning tree has a path from every node to every other node,
  536.     and no cycles, hence, it corresponds to a perfect maze.
  537.  
  538. Don Gillies - gillies@cs.uiuc.edu - University of Illinois at Urbana-Champaign
  539.  
  540.  
  541.  
  542.  
  543. ========================================
  544.  
  545.  
  546.  
  547.  
  548.  
  549. Excerpts from programming: 8-Apr-92 re mazes Chris_Okasaki@LOCH.MESS. (5437)
  550.  
  551. Thanks for the messages.  FYI, here is the maze tutorial I used to send out.
  552.  
  553. Chris
  554. --------------
  555. This seems to come up every couple of months, doesn't it?  Maybe we
  556. should make a FAQL for this group...
  557.  
  558. Anyway, maze generation--a topic near and dear to my heart!  I'm going
  559. to describe the three most common methods.  Note that these will all
  560. generate mazes without loops or rooms or anything like that.  Restricting
  561. a maze to be a tree (in the graph-theoretical sense of the term) simplifies
  562. things immensely.  Mazes with loops are much harder to generate automatically
  563. in any nice way.  Perhaps the best way is start out generating a tree and
  564. then knock a couple of extra walls (all the algorithms start out with all
  565. walls present and then knock out walls as necessary).
  566.  
  567. Finally, note that all of these techniques are based on well-known graph
  568. algorithms.  This isn't surprising since what is being generated is
  569. really nothing more than a spanning tree.
  570.  
  571.  
  572. Technique #1: Depth-first search
  573.  
  574. 1. Pick a random starting location as the "current cell" and mark it
  575.    as "visited".  Also, initialize a stack of cells to empty (the stack
  576.    will be used for backtracking).  Initialize VISITED (the number of
  577.    visited cells) to 1.
  578. 2. While VISITED < the total number of cells, do the following:
  579.      If the current cell has any neighbors which haven't yet been visited,
  580.        pick one at random.  Push the current cell on the stack and set the
  581.        current cell to be the new cell, marking the new cell as visited.
  582.        Knock out the wall between the two cells.  Increment VISITED.
  583.      If all of the current cell's neighbors have already been visited, then
  584.        backtrack.  Pop the previous cell off the stack and make it the current
  585.        cell.
  586.  
  587.  
  588. This algorithm is probably the simplest to implement, but it has a problem
  589. in that there are many mazes which it cannot generate.  In particular, it will
  590. continue generating one branch of the maze as long as there are unvisited cells
  591. in the area instead of being able to give up and let the unvisited cells get
  592. used by a different branch.  This can be partially remedied by allowing the
  593. algorithm to randomly backtrack even when there are unvisited neighbors, but
  594. this creates the possibility of (potentially large) dead spaces in the
  595. maze.  For some applications, such as dungeon creation, this behavior
  596. might be desirable.  A refinement which cuts down on the amount of dead space
  597. is to vary the probability of backtracking as an increasing function on the
  598. number of iterations since the last backtrack.
  599.  
  600.  
  601.  
  602. Technique #2: Prim's Algorithm
  603. 1. Maintain three sets of cells: IN, OUT, and FRONTIER.  Initially, choose
  604.    one cell at random and place it in IN.  Place all of the cell's neighbors in
  605.    FRONTIER and all remaining cells in OUT.
  606. 2. While FRONTIER is not empty do the following:  Remove one cell at random
  607.    from FRONTIER and place it in IN.  If the cell has any neighbors in
  608.    OUT, remove them from OUT and place them in FRONTIER.  The cell is
  609.    guaranteed to have at least one neighbor in IN (otherwise it would
  610.    not have been in FRONTIER); pick one such neighbor at random and connect
  611.    it to the new cell (ie knock out a wall).
  612.  
  613. This algorithm works by growing a single tree (without concentrating
  614. on any one particular branch like the previous algorithm).  An interesting
  615. variation on this algorithm is to run two (or more) instances of it
  616. at once, starting in different locations and generating non-interesecting
  617. trees.  This can be useful, for instance, for generating multiple disjoint
  618. areas on a single level of a dungeon (perhaps connected by secret doors
  619. or perhaps requiring adventurers to blast through walls themselves).
  620.  
  621.  
  622. Technique #3: Kruskal's Algorithm
  623.  
  624. This is perhaps the most advanced of the maze generation algorithms,
  625. requiring some knowledge of the union-find algorithm.  It is also the
  626. most fun to watch in progress!
  627.  
  628. Basically what the union-find algorithm does is give you a FAST
  629. implementation of equivalence classes where you can do two things:
  630. FIND which equivalence class a given object belongs to, or UNION
  631. two equivalance classes into a single class.  Any moderately advanced
  632. book on algorithms and data structures will have more details.
  633. In this algorithm, the objects will be cells in the maze, and two
  634. objects will be in the same equivalence class iff they are (perhaps
  635. indirectly) connected.
  636.  
  637. 1. Initialize the union-find structures so that every cell is in
  638.    its own equivalence class.  Create a set containing all the interior
  639.    walls of the maze (ie those walls which lie between neighboring cells).
  640.    Set COUNT to the number of cells.  (COUNT is the number of connected
  641.    components in the maze).
  642. 2. While COUNT > 1 do the following:
  643.      Remove a wall from the set of walls at random.  If the two cells
  644.      that this wall separates are already connected (test by doing a FIND
  645.      on each), then do nothing; otherwise, connect the two cells (by
  646.      UNIONing them and decrementing COUNT) and knock out the wall.
  647.  
  648.  
  649.  
  650. Note that none of these algorithms make any assumptions about the topology
  651. of the maze.  They will work with 2-d or 3-d grids, toroids, hexagons,
  652. whatever.  However, in the more highly connected topologies (such as 3-d
  653. grids), the deficiencies of the first algorithm will become even more apparent
  654. (it will tend to produce long, winding paths with very little branching).
  655.  
  656.  
  657. Have fun with these!
  658.  
  659. Chris
  660.  
  661.  
  662. ================================
  663. /*
  664.  * maz.c - generate a maze
  665.  *
  666.  * algorithm posted to rec.games.programmer by jallen@ic.sunysb.edu
  667.  * program cleaned and reorganized by mzraly@ldbvax.dnet.lotus.com
  668.  *
  669.  * don't make people pay for this, or I'll jump up and down and
  670.  * yell and scream and embarass you in front of your friends...
  671.  *
  672.  * compile: cc -o maz -DDEBUG maz.c
  673.  *
  674.  */
  675. #include <stdio.h>
  676.  
  677. static int      multiple = 57;  /* experiment with this? */
  678. static int      offset = 1;     /* experiment with this? */
  679.  
  680. #ifdef __STDC__
  681. int maze(char maz[], int y, int x, char vc, char hc, char fc);
  682. void mazegen(int pos, char maz[], int y, int x, int rnd);
  683. #else
  684. int maze();
  685. void mazegen();
  686. #endif
  687.  
  688. /*
  689.  * maze() : generate a random maze of size (y by x) in maz, using vc as the
  690.  * vertical character, hc as the horizontal character, and fc as the floor
  691.  * character
  692.  *
  693.  * maz is an array that should already have its memory allocated - you could
  694.  * malloc a char string if you like.
  695.  */
  696. #ifdef __STDC__
  697. int maze(char maz[], int y, int x, char vc, char hc, char fc)
  698. #else
  699. int maze(maz, y, x, vc, hc, fc)
  700. char            maz[], vc, hc, fc;
  701. int             y, x;
  702. #endif
  703. {
  704.    int             i, yy, xx;
  705.    int             max = (y * x);
  706.    int             rnd = time(0L);
  707.  
  708.    /* For now, return error on even parameters */
  709.    /* Alternative is to decrement evens by one */
  710.    /* But really that should be handled by caller */
  711.    if (!(y & 1) | !(x & 1))
  712.       return (1);
  713.  
  714.    /* I never assume... */
  715.    for (i = 0; i < max; ++i)
  716.       maz[i] = 0;
  717.  
  718.    (void) mazegen((x + 1), maz, y, x, rnd);
  719.  
  720.    /* Now replace the 1's and 0's with appropriate chars */
  721.    for (yy = 0; yy < y; ++yy) {
  722.       for (xx = 0; xx < x; ++xx) {
  723.          i = (yy * x) + xx;
  724.  
  725.          if (yy == 0 || yy == (y - 1))
  726.             maz[i] = hc;
  727.          else if (xx == 0 || xx == (x - 1))
  728.             maz[i] = vc;
  729.          else if (maz[i] == 1)
  730.             maz[i] = fc;
  731.          else if (maz[i - x] != fc && maz[i - 1] == fc
  732.                  && (maz[i + x] == 0 || (i % x) == (y - 2)))
  733.             maz[i] = vc;
  734.          else
  735.             maz[i] = hc;       /* for now... */
  736.       }
  737.    }
  738.    return (0);
  739. }
  740.  
  741.  
  742. /*
  743.  * mazegen : do the recursive maze generation
  744.  *
  745.  */
  746. #ifdef __STDC__
  747. void mazegen(int pos, char maz[], int y, int x, int rnd)
  748. #else
  749. void
  750. mazegen(pos, maz, y, x, rnd)
  751.    int             pos, y, x, rnd;
  752.    char            maz[];
  753. #endif
  754. {
  755.    int             d, i, j;
  756.  
  757.    maz[pos] = 1;
  758.    while (d = (pos <= x * 2 ? 0 : (maz[pos - x - x] ? 0 : 1))
  759.           | (pos >= x * (y - 2) ? 0 : (maz[pos + x + x] ? 0 : 2))
  760.           | (pos % x == x - 2 ? 0 : (maz[pos + 2] ? 0 : 4))
  761.           | (pos % x == 1 ? 0 : (maz[pos - 2] ? 0 : 8))) {
  762.  
  763.       do {
  764.          rnd = (rnd * multiple + offset);
  765.          i = 3 & (rnd / d);
  766.       } while (!(d & (1 << i)));
  767.  
  768.       switch (i) {
  769.       case 0:
  770.          j = -x;
  771.          break;
  772.       case 1:
  773.          j = x;
  774.          break;
  775.       case 2:
  776.          j = 1;
  777.          break;
  778.       case 3:
  779.          j = -1;
  780.          break;
  781.       default:
  782.          break;
  783.       }
  784.  
  785.       maz[pos + j] = 1;
  786.  
  787.       mazegen(pos + 2 * j, maz, y, x, rnd);
  788.    }
  789.  
  790.    return;
  791. }
  792. #ifdef DEBUG
  793. #define MAXY 24
  794. #define MAXX 80
  795.  
  796. #ifdef __STDC__
  797. main(int argc, char *argv[])
  798. #else
  799. main(argc, argv)
  800.    int             argc;
  801.    char           *argv[];
  802. #endif
  803. {
  804.    extern int      optind;
  805.    extern char    *optarg;
  806.    int             x = 79;
  807.    int             y = 23;
  808.    char            hor = '-';
  809.    char            ver = '|';
  810.    char            flo = ' ';
  811.    char            maz[MAXY * MAXX];
  812.    int             i;
  813.  
  814.    while ((i = getopt(argc, argv, "h:v:f:y:x:m:o:")) != EOF)
  815.       switch (i) {
  816.       case 'h':
  817.          hor = *optarg;
  818.          break;
  819.       case 'v':
  820.          ver = *optarg;
  821.          break;
  822.       case 'f':
  823.          flo = *optarg;
  824.          break;
  825.       case 'y':
  826.          y = atoi(optarg);
  827.          break;
  828.       case 'x':
  829.          x = atoi(optarg);
  830.          break;
  831.       case 'm':
  832.          multiple = atoi(optarg);
  833.          break;
  834.       case 'o':
  835.          offset = atoi(optarg);
  836.          break;
  837.       case '?':
  838.       default:
  839.          (void) fprintf(stderr, "usage: maz [xyhvfmo]\n");
  840.          break;
  841.       }
  842.  
  843.    if (maze(maz, y, x, ver, hor, flo) == 0) {
  844.       for (i = 0; i < (x * y); ++i) {
  845.          (void) putchar(maz[i]);
  846.          if (((i + 1) % x) == 0)
  847.             (void) putchar('\n');
  848.       }
  849.    } else {
  850.       (void) fprintf(stderr, "Couldn't make the maze\n");
  851.    }
  852.  
  853.    exit(0);
  854. }
  855. #endif DEBUG
  856.  
  857.          hor = *optarg;
  858.          break;
  859.       case 'v':
  860.          ver = *optarg;
  861.          break;
  862.       case 'f':
  863.          flo = *optarg;
  864.          break;
  865.       case 'y':
  866.          y = atoi(optarg);
  867.          break;
  868.       case 'x':
  869.          x = atoi(optarg);
  870.          break;
  871.       case 'm':
  872.          multiple = atoi(optarg);
  873.          break;
  874.       case 'o':
  875.          offset = atoi(optarg);
  876.          break;
  877.       case '?':
  878.       default:
  879.          (void) fprintf(stderr, "usage: maz [xyhvfmo]\n");
  880.          break;
  881.       }
  882.  
  883.    if (maze(maz, y, x, ver, hor, flo) == 0) {
  884.       for (i = 0; i < (x * y); ++i) {
  885.          (void) putchar(maz[i]);
  886.          if (((i + 1) % x) == 0)
  887.             (void) putchar('\n');
  888.       }
  889.    } else {
  890.       (void) fprintf(stderr, "Couldn't make the maze\n");
  891.    }
  892.  
  893.    exit(0);
  894. }
  895. #endif DEBUG
  896.