Generating and solving a 2D maze is a surprisingly simple task. In order to first create a maze with a single unique solution, we define a maze, , with dimensions
by
, to be an array of “cells”, which have four “sides”. Each side is a set of parameters:
- Border: whether or not that side is part of the outlying border surrounding the maze.
- Wall: whether or not that side is a wall which cannot be traversed.
- Solution: whether or not that side is an open area which is part of the path one takes to reach the end up the maze successfully.
- Backtrack: whether or not that size is an open area which has been traversed, but is not part of the “solution” path.
- Coordinates: the [x,y] coordinates of the cell.
With these definitions in place, generating a maze is quite simple.
- Create a stack structure to hold a set of type “cell”.
- For each cell
- For each side
- Set all walls.
- Clear all solutions and backtracks.
- Set the coordinates appropriately.
- Set the borders appropriately.
- Create an index to keep track of the number of “visited” cells,
, and set it to zero.
- Calculate the total number of cells,
.
- Pick an arbitrary starting point in the maze,
.
- Define the current cell under analysis,
, as the cell located at
.
- While
:
- Push the coordinates of
onto the stack.
- Mark
as “visited”.
- Generate a list of all the neighbouring cells of
with all four of their own walls untouched,
.
- If
- Randomly pick an element of
.
- Push
onto the stack.
- Smash down just the one wall between
and
.
- Set
to be
.
- Randomly pick an element of
- Else
- Pop the top item off of the stack, and set
to be equal to it.
- Pop the top item off of the stack, and set
- EndIf
- Push the coordinates of
- EndWhile
- For each side
The end result is a long winding maze where there is only a single unique path between any two points. Solving it is also very straight forward. We pick a start and end point, and repeat the depth-first search while keeping track of cells we’ve already visited. When we finally find the destination, we backtrack to the starting point, indicating whether part of our backtrack is part of the solution path.
A final note: the depth-first search tends to generate long paths that are easy to solve even by hand. If you wish to generate more complicated mazes, consider doing a breadth-first search in the maze generation. Doing so is just a matter of swapping out the stack with a queue, and the majority of the pseudo code described above remains unchanged.
An animation demonstrating this algorithm is shown below, along with the original source code used to generate it. The animated GIF was generated by printing the entire maze to a series of text files and using ImageMagick to create the individual frames of animation and combine them into a GIF.

Maze generation and solving animation
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 |
#ifndef MAZE_H // Prevent multiple inclusions #define MAZE_H /******************************************************************************* * Preprocessor Directives ******************************************************************************/ #include <stdint.h> #include "stack.h" /******************************************************************************* * Macros and Constants ******************************************************************************/ /* Directional bit identities */ #define WEST (0x1<<3) #define SOUTH (0x1<<2) #define EAST (0x1<<1) #define NORTH (0x1<<0) #define BITMAP_SIZE (3) /******************************************************************************* * Abstract Data Types ******************************************************************************/ typedef struct status_t { uint16_t backtrack : 4; uint16_t solution : 4; uint16_t border : 4; uint16_t wall : 4; } status_t; typedef struct cell_t { status_t status; int x; int y; int bVisited; char bitmap[BITMAP_SIZE][BITMAP_SIZE]; } cell_t; typedef struct maze_t { cell_t** maze; stack_t stack; int xMax; int yMax; int totalCells; } maze_t; /******************************************************************************* * Public Function Prototypes *******************************************************************************/ /* Handle compiling C code as part of a C++ project */ #ifdef __cplusplus extern "C" { #endif /* @functionName: stackInit * @brief: Initializes an empty stack. * @param: stk: A pointer to the stack. */ //int stackInit(stack_t* stk); int mazeInit(maze_t* maze, size_t width, size_t height); int mazeDestroy(maze_t* maze); int mazeSolve(maze_t* maze); void mazeRender(maze_t* m); #ifdef __cplusplus } #endif #endif // MAZE_H |
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 564 565 566 567 568 569 570 571 572 573 574 575 576 577 578 579 580 581 582 583 584 585 586 587 588 589 590 591 592 593 594 595 596 597 598 599 600 601 602 603 604 605 606 607 608 609 610 611 612 613 614 615 616 617 618 619 620 621 622 623 624 625 626 627 628 629 630 631 632 633 634 635 636 637 638 |
/******************************************************************************* * @file: maze.c * @author: Matthew Giassa * @email: matthew@giassa.net * @copyright: Matthew Giassa, 2009 * @brief: Used to generate and solve perfect mazes (every space utilized) * as part of a robotic mouse-in-a-maze robotic vision project. */ /******************************************************************************* * Preprocessor Directives ******************************************************************************/ /* System Includes */ #include <stdio.h> #include <errno.h> #include <stdlib.h> #include <string.h> #include <time.h> #include <stdbool.h> #include <unistd.h> #include <linux/limits.h> /* Project Includes */ #include "inc/linked_list.h" #include "inc/maze.h" /******************************************************************************* * Macros and Constants ******************************************************************************/ #define EOK (0) #define ANIMATION_DELAY_US (50000) //#define RENDER_GIF //#define ANIMATED_ON_SCREEN static int outCount = 0; /******************************************************************************* * Abstract Data Types ******************************************************************************/ typedef struct coords_t { int x; int y; } coords_t; typedef uint8_t direction_t; /******************************************************************************* * Private Function Prototypes ******************************************************************************/ /* Tells us if two cells are within the extremities of an array ie: [0, dimMax] * so a future operation does trigger a segfault due to addressing invalid * memory. */ bool inRange(int x, int y, int xMax, int yMax); /* Tells us if two cells are in range of each other (ie: 4-connected * neighbours. */ bool isConnected4(int x1, int y1, int x2, int y2); /* Takes a pair of coordinates, and if they are 4-neighbours, converts the * coordinates into a constants representing one of 4 cartesian unit vectors. */ direction_t direction(int x1, int y1, int x2, int y2); /* Provides the inverse of the the direction() function. */ direction_t reverseDirection(int dir); /* Tells us if it is possible to travel from one location to another, taking * into account whether there is a wall between the two coordinates. */ bool isAccessible(int x1, int y1, status_t status1, int x2, int y2, status_t status2); /******************************************************************************* * Function Definitions ******************************************************************************/ /*----------------------------------------------------------------------------*/ int main(void) { maze_t maze = { 0 }; /* Initialize random seed */ srand(time(NULL)); setbuf(stdout, NULL); /* Determine size of map to generate */ const int x = 16; const int y = 9; /* Generate random maze */ if (mazeInit(&maze, x, y) != EOK) { printf("Failed to generate maze.\n"); return (-EIO); } else { system("clear"); } /* Solve the maze */ mazeSolve(&maze); /* Print maze to screen */ mazeRender(&maze); /* Clean up */ mazeDestroy(&maze); #ifdef RENDER_GIF system("convert *.png -set delay 10 output.gif"); #endif return EOK; } /*----------------------------------------------------------------------------*/ int mazeInit(maze_t* m, size_t width, size_t height) { if (!m || width <= 0 || height <= 0) { return (-EINVAL); } int i, j, k, a, b, ret = EOK; llist_t list = { 0 }; /* For storing "neighbours" during generation */ bool bErr = false; int iVisited = 0; coords_t cur; /* Initialize and dynamically allocate memory as needed */ if (stackInit(&m->stack) != EOK) { bErr = true; } /* Store dimensions */ m->xMax = width; m->yMax = height; m->totalCells = m->xMax * m->yMax; if (!bErr) { if ((m->maze = (cell_t**)calloc(m->xMax, sizeof(cell_t*))) == NULL) { bErr = true; } for (i=0; i<m->xMax; i++) { if ((m->maze[i] = (cell_t*)calloc(m->yMax, sizeof(cell_t))) == NULL) { bErr = true; break; } } } /* Populate cells with coordinates, walls */ for (i=0; i<m->xMax; i++) { for (j=0; j<m->yMax; j++) { m->maze[i][j].x = j; m->maze[i][j].y = i; m->maze[i][j].bVisited = false; /* Build all walls */ m->maze[i][j].status.wall = NORTH | SOUTH | EAST | WEST; } } /* Populate borders */ for (i=0; i<m->xMax; i++) { a = i; b = 0; m->maze[a][b].status.border |= NORTH; } for (i=0; i<m->xMax; i++) { a = i; b = m->yMax-1; m->maze[a][b].status.border |= SOUTH; } for (i=0; i<m->yMax; i++) { a = 0; b = i; m->maze[a][b].status.border |= WEST; } for (i=0; i<m->yMax; i++) { a = m->xMax-1; b = i; m->maze[a][b].status.border |= EAST; } /* Start depth-first-search generation of maze */ cur.x = 0; cur.y = 0; iVisited = 1; /* Evaluate all cells in maze to make this a "perfect" maze with a unique * path between any two arbitrary points in the maze. */ while (iVisited < m->totalCells) { (void)llistInit(&list); for (i=-1; i<=1; i++) { for (j=-1; j<=1; j++) { /* Scan all valid neighboring cells */ if ((i==0) && (j==0)) { continue; } /* Make sure we don't try to address out-of-bounds memory via * sloppy indexing. */ if (inRange(cur.x+i, cur.y+j, m->xMax, m->yMax)) { /* Are the two cells 4-neighbours */ if (isConnected4(cur.x, cur.y, cur.x+i, cur.y+j)) { /* Are all 4 walls for the cell intact */ if (m->maze[cur.x+i][cur.y+j].status.wall == (NORTH | SOUTH | WEST | EAST)) { /* All walls are intact; Add cell coordinates to list */ lnode_t tmp; coords_t coords; coords.x = cur.x+i; coords.y = cur.y+j; tmp.width = sizeof(coords_t); tmp.data = &coords; if (EOK != llistInsert(&list, &tmp)) { printf("INSERT ERROR\n"); } } } } } } /* Show maze being generated */ #ifdef ANIMATED_ON_SCREEN mazeRender(m); #endif /* Found a valid unvisited 4-neighbour cell */ if (list.length > 0) { /* Pick a random cell from the list of neighbouring cells with intact walls */ int offset = rand() % list.length; lnode_t* tmp = list.head; for (k=0; k<offset; k++) { tmp = tmp->next; } /* Knock down the wall between the current cell and the random neighbour */ coords_t* newCoords = (coords_t*)tmp->data; cell_t* currentCell = &m->maze[cur.x][cur.y]; cell_t* neighbourCell = &m->maze[newCoords->x][newCoords->y]; direction_t dir = direction(cur.x, cur.y, newCoords->x, newCoords->y); currentCell->status.wall &= ~dir; neighbourCell->status.wall &= ~reverseDirection(dir); /* Push current cell on to the stack now that walls are knocked down */ snode_t node = { 0 }; node.data = &cur; node.width = sizeof(coords_t); stackPush(&m->stack, &node); cur.x = newCoords->x; cur.y = newCoords->y; iVisited++; } else { /* Pop the top entry from the stack, set to current coordinates */ snode_t node = { 0 }; stackPop(&m->stack, &node); coords_t* coords = node.data; cur.x = coords->x; cur.y = coords->y; free(node.data); } /* Clean up temporary list */ (void)llistDestroy(&list); } /* Cleanup on error */ if (bErr) { for (i=0; i<m->yMax; i++) { free(m->maze[i]); m->maze[i] = NULL; } free(m->maze); m->maze = NULL; ret = (-ENOMEM); } /* Cleanup stack */ stackDestroy(&m->stack); return ret; } /*----------------------------------------------------------------------------*/ int mazeSolve(maze_t* m) { if (!m) { return (-EINVAL); } int i, j; int ret = EOK; llist_t list = { 0 }; /* For storing "neighbours" during generation */ bool bFound = false; bool bErr = false; coords_t cur, sol; coords_t* next; /* Initialize and dynamically allocate memory as needed */ if (stackInit(&m->stack) != EOK) { return (-EIO); } /* Start depth-first-search generation of maze */ cur.x = 0; cur.y = 0; sol.x = m->xMax-1; sol.y = m->yMax-1; m->maze[cur.x][cur.y].bVisited = true; while (!bFound && !bErr) { (void)llistInit(&list); for (i=-1; i<=1; i++) { for (j=-1; j<=1; j++) { /* Scan all valid neighboring cells */ if ((i==0) && (j==0)) { continue; } if ((cur.x == sol.x) && (cur.y == sol.y)) { bFound = true; continue; } /* Make sure we don't try to address out-of-bounds memory via * sloppy indexing. */ if (inRange(cur.x+i, cur.y+j, m->xMax, m->yMax)) { /* Are the two cells 4-neighbours */ if (isConnected4(cur.x, cur.y, cur.x+i, cur.y+j)) { /* Is the destination cell unvisited */ if (!m->maze[cur.x+i][cur.y+j].bVisited) { /* Is the neighbouring cell accessible (ie: no walls in the way) */ if (isAccessible(cur.x, cur.y, m->maze[cur.x][cur.y].status, cur.x+i, cur.y+j, m->maze[cur.x+i][cur.y+j].status)) { lnode_t tmp; coords_t coords; coords.x = cur.x+i; coords.y = cur.y+j; tmp.width = sizeof(coords_t); tmp.data = &coords; if (EOK != llistInsert(&list, &tmp)) { printf("INSERT ERROR\n"); } } } } } } } /* Show maze being solved */ #ifdef ANIMATED_ON_SCREEN mazeRender(m); #endif /* Handle completion when end of maze is found */ if (bFound) { /* Process entire stack */ while (m->stack.top != NULL) { /* Show maze being solved */ #ifdef ANIMATED_ON_SCREEN mazeRender(m); #endif snode_t node = { 0 }; if (stackPop(&m->stack, &node) == EOK) { coords_t* coords = node.data; printf("Coordinates of solution path: [%02d,%02d]\n", coords->x, coords->y); direction_t dir = direction(cur.x, cur.y, coords->x, coords->y); if (bFound) { m->maze[cur.x][cur.y].status.solution |= dir; } cur.x = coords->x; cur.y = coords->y; if (bFound) { m->maze[cur.x][cur.y].status.solution |= reverseDirection(dir); } free(node.data); } } } else { /* Still searching the maze */ if (list.length > 0) { /* Found a valid accessible 4-neighbour cell. Pick a random cell * from the list of valid cells. */ int offset = rand() % list.length; int k; lnode_t* tmp = list.head; for (k=0; k<offset; k++) { tmp = tmp->next; } next = (coords_t*)tmp->data; /* Push current cell on to the stack */ snode_t node = { 0 }; node.data = &cur; node.width = sizeof(coords_t); if (stackPush(&m->stack, &node) != EOK) { printf("Stack push error; Aborting\n"); bErr = true; } direction_t dir = direction(cur.x, cur.y, next->x, next->y); m->maze[cur.x][cur.y].status.backtrack |= dir; cur.x = next->x; cur.y = next->y; m->maze[cur.x][cur.y].status.backtrack = reverseDirection(dir); m->maze[cur.x][cur.y].bVisited = true; } else { /* Pop the top entry from the stack, set to current coordinates */ snode_t node = { 0 }; if (stackPop(&m->stack, &node) == EOK) { coords_t* coords = node.data; cur.x = coords->x; cur.y = coords->y; free(node.data); } else { printf("Could not pop node\n"); bErr = true; } } } /* Clean up temporary list */ (void)llistDestroy(&list); } /* Cleanup on error */ stackDestroy(&m->stack); return ret; } /*----------------------------------------------------------------------------*/ void mazeRender(maze_t* m) { if (!m) { return; } int i, j, k, l; int dirSides[4] = { WEST, SOUTH, EAST, NORTH }; coords_t coordSides[4] = { {0, 1}, {1, 2}, {2, 1}, {1, 0} }; int dirDiags[4] = { NORTH | WEST, SOUTH | WEST, NORTH | EAST, SOUTH | EAST }; coords_t coordDiags[4] = { {0, 0}, {0, 2}, {2, 0}, {2, 2} }; cell_t* c; direction_t wall, sol, bt, border; /* Generate bitmaps for each cell */ for (j=0; j<m->yMax; j++) { for (i=0; i<m->xMax; i++) { c = &m->maze[i][j]; wall = c->status.wall; sol = c->status.solution; bt = c->status.backtrack; border = c->status.border; /* Sanity check */ for (k=0; k<4; k++) { if (((wall & dirSides[k]) || (border & dirSides[k])) && ((bt & dirSides[k]) || (sol & dirSides[k]))) { /* Cannot have a portion of the cell be simultaneously a wall/border * and a solution/backtrack area (mutually exclusive). */ printf("Portion of maze is broken\n"); } } /* Set sides */ for (k=0; k<4; k++) { if (sol & dirSides[k]) { c->bitmap[coordSides[k].x][coordSides[k].y] = '*'; } else if (bt & dirSides[k]) { c->bitmap[coordSides[k].x][coordSides[k].y] = '.'; } else if (border & dirSides[k]) { c->bitmap[coordSides[k].x][coordSides[k].y] = '='; } else if (wall & dirSides[k]) { c->bitmap[coordSides[k].x][coordSides[k].y] = '#'; } else { c->bitmap[coordSides[k].x][coordSides[k].y] = ' '; } } /* Set corners */ for (k=0; k<4; k++) { if (border & dirDiags[k]) { c->bitmap[coordDiags[k].x][coordDiags[k].y] = '='; } else { c->bitmap[coordDiags[k].x][coordDiags[k].y] = '#'; } } /* Set centre */ if (sol) { c->bitmap[1][1] = '*'; } else if (bt) { c->bitmap[1][1] = '.'; } else { c->bitmap[1][1] = ' '; } } } char* buf; size_t bufsize = (BITMAP_SIZE*BITMAP_SIZE*(m->xMax)*(m->yMax)) + (BITMAP_SIZE*m->yMax); if ((buf = calloc(bufsize, sizeof(char))) == NULL) { /* Couldn't allocate output buffer; Abort */ return; } /* Render maze */ int cnt = 0; for (j=0; j<m->yMax; j++) { for (l=0; l<BITMAP_SIZE; l++) { for (i=0; i<m->xMax; i++) { c = &m->maze[i][j]; for (k=0; k<BITMAP_SIZE; k++) { buf[cnt++] = c->bitmap[k][l]; } } buf[cnt++] = '\n'; } } #ifdef RENDER_GIF FILE* fp; char txtname[PATH_MAX]; char picname[PATH_MAX]; char command[PATH_MAX]; sprintf(txtname, "%04d.txt", outCount); sprintf(picname, "%04d.png", outCount); outCount++; if ((fp = fopen(txtname, "w")) != NULL) { fprintf(fp, "%s", buf); fclose(fp); sprintf(command, "convert -font Courier -pointsize 12 \"label:@%s\" %s", txtname, picname); system(command); } #endif /* Print buffer to screen */ write(STDOUT_FILENO, buf, strlen(buf)); printf("\n"); fflush(stdout); usleep(ANIMATION_DELAY_US); system("clear"); } /*----------------------------------------------------------------------------*/ int mazeDestroy(maze_t* m) { if (!m) { return (-EINVAL); } int i; stackDestroy(&m->stack); for (i=0; i<m->xMax; i++) { free(m->maze[i]); m->maze[i] = NULL; } free(m->maze); m->maze = NULL; return EOK; } /*----------------------------------------------------------------------------*/ bool inRange(int x, int y, int xMax, int yMax) { return ((x >= 0) && (y >= 0) && (x <= xMax-1) && (y <= yMax - 1)); } /*----------------------------------------------------------------------------*/ bool isConnected4(int x1, int y1, int x2, int y2) { return ( ((x1 == x2) && (y1 == y2+1)) || ((x1 == x2) && (y1 == y2-1)) || ((x1 == x2+1) && (y1 == y2)) || ((x1 == x2-1) && (y1 == y2)) ); } /*----------------------------------------------------------------------------*/ bool isAccessible(int x1, int y1, status_t status1, int x2, int y2, status_t status2) { bool ret = false; if ((x1 == x2) && (y1 == y2-1)) { if (!(status1.wall & SOUTH) && !(status2.wall & NORTH)) { ret = true; } } if( (x1 == x2) && (y1 == y2+1)) { if (!(status1.wall & NORTH) && !(status2.wall & SOUTH)) { ret = true; } } if ((x1 == x2+1) && (y1 == y2)) { if (!(status1.wall & WEST) && !(status2.wall & EAST)) { ret = true; } } if ((x1 == x2-1) && (y1 == y2)) { if (!(status1.wall & EAST) && !(status2.wall & WEST)) { ret = true; } } return ret; } /*----------------------------------------------------------------------------*/ direction_t direction(int x1, int y1, int x2, int y2) { direction_t ret = 0xff; if (x1 == x2) { if (y2 == y1+1) { ret = SOUTH; } else if (y2 == y1-1) { ret = NORTH; } } if (y1 == y2) { if (x2 == x1 -1) { ret = WEST; } else if (x2 == x1+1) { ret = EAST; } } return ret; } /*----------------------------------------------------------------------------*/ direction_t reverseDirection(int dir) { direction_t ret = 0xFF; switch(dir) { case NORTH: ret = SOUTH; break; case SOUTH: ret = NORTH; break; case EAST: ret = WEST; break; case WEST: ret = EAST; break; default: break; } return ret; } |
Can you post the missing files for your list implementation?
Hi. Those files will be up in a short bit under the “Algorithms” category.