#include <stdio.h>
#include <time.h>
#define MaxSize 12
#define luck() (6<<27 < rand())

int main(void)
{
  char RIGHT_WALL, BELOW_WALL; /* holds the 2 characters printed for each cell */
  int temp,
      H,			/* height of the maze */
      C,			/* current cell */
      E;			/* temporary pointer used in the updating */
  static int L[MaxSize+1],R[MaxSize+1];        /* left and right pointers */

  srand((unsigned int)time(NULL));
  L[1] = 1;
  H = MaxSize;		/* reads height and sets L[1] to 1 */
  printf("%3d: ", H);
  E = MaxSize-1;
  while (E != 0) {
    R[E+1] = E;
    L[E+1] = E;
    printf("._");			/* close top of maze */
    --E;
  }
  printf("\n%3d: |", H);
  H = MaxSize-1;
  while (H != 0) {                         /* more rows to do */
    C = MaxSize-1;
    while (C != 0) { /* visit cells from left to right */
      E=L[C];
      if ((C != E) && luck()) {  /* make right-connection ? */
        temp = R[C+1];			/* link E */
        R[E+1] = temp;			/* link E */
        L[temp+1] = E;			/* to R[C+1] */
        R[C+1] = C-1;			/* link C */
        L[C] = C;			/* to C-1 */
        RIGHT_WALL = '.';			/* no wall to the right */
      } else {
        RIGHT_WALL = '|';			/* wall to the right */
      }
      E=L[C+1];
      if ((C != E) && luck()) {    /* omit down-connection ? */
        temp = R[C+1];			/* link E */
        R[E+1] = temp;			/* link E */
        L[temp+1] = E;			/* to R[C+1] */
        L[C+1] = C;			/* link C */
        R[C+1] = C;			/* to C */
        BELOW_WALL = '_';			/* wall downward */
      } else {
        BELOW_WALL = ' ';			/* no wall downward */
      }
      printf("%c%c", BELOW_WALL, RIGHT_WALL);
      --C;
    }
    printf("\n%3d: |", H);
    --H;
  }
  BELOW_WALL = '_';				/* close bottom of maze */
  C = MaxSize-1;
  while (C != 0) {              /* bottom row */
    E=L[C];
    if ((C != E) && (C == R[C+1] || luck())) {
      temp=R[C+1];
      R[E+1]=temp;
      L[temp+1]=E;
      temp=C-1;
      R[C+1]=temp;
      L[temp+1]=C;
      RIGHT_WALL = '.';
    } else {
      RIGHT_WALL = '|';
    }
    printf("_%c", RIGHT_WALL);
    E = L[C+1];
    temp = R[C+1];
    R[E+1] = temp;
    L[temp+1] = E;
    L[C+1] = C;
    R[C+1] = C;
    --C;
  }
  printf("\n");
}