Maze Generation & Solving

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, $A$, with dimensions $m$ by $n$, 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, $v$, and set it to zero.
• Calculate the total number of cells, $T=mn$.
• Pick an arbitrary starting point in the maze, $[i,j]$.
• Define the current cell under analysis, $C$, as the cell located at $[i,j]$.
• While $v \le T$:
• Push the coordinates of $C$ onto the stack.
• Mark $C$ as “visited”.
• Generate a list of all the neighbouring cells of $C$ with all four of their own walls untouched, $L$.
• If $\|L\| \geq 1$
• Randomly pick an element of $L$.
• Push $C$ onto the stack.
• Smash down just the one wall between $C$ and $L$.
• Set $C$ to be $L$.
• Else
• Pop the top item off of the stack, and set $C$ to be equal to it.
• EndIf
• EndWhile

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

```#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
```

```/*******************************************************************************
* @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/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;
}

```

2 thoughts on “Maze Generation & Solving”

• Hi. Those files will be up in a short bit under the “Algorithms” category.