Maze generation algorithms are automated methods for the creation of mazes.

Graph theory based methods

A maze can be generated by starting with a predetermined arrangement of cells (most commonly a rectangular grid but other arrangements are possible) with wall sites between them. This predetermined arrangement can be considered as a connected graph with the edges representing possible wall sites and the nodes representing cells. The purpose of the maze generation algorithm can then be considered to be making a subgraph in which it is challenging to find a route between two particular nodes.

If the subgraph is not connected, then there are regions of the graph that are wasted because they do not contribute to the search space. If the graph contains loops, then there may be multiple paths between the chosen nodes. Because of this, maze generation is often approached as generating a random spanning tree. Loops, which can confound naive maze solvers, may be introduced by adding random edges to the result during the course of the algorithm.

Algorithm Visualization

The animation shows the maze generation steps for a graph that is not on a rectangular grid. First, the computer creates a random planar graph G shown in blue, and its dual F shown in yellow. Second, computer traverses F using a chosen algorithm, such as a depth-first search, coloring the path red. During the traversal, whenever a red edge crosses over a blue edge, the blue edge is removed. Finally, when all vertices of F have been visited, F is erased and two edges from G, one for the entrance and one for the exit, are removed.

References

Implementations

  • 1
    
    # TODO: Implement in Python
    
  • 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
    
    const n = 6; // rows (change these!)
    const m = 6; // columns (change these!)
    
    const hEnd = m * 4 - (m - 1);
    const vEnd = n * 3 - (n - 1);
    
    const G = [];
    
    for (let i = 0; i < vEnd; i++) { // by row
      G[i] = new Array(hEnd);
      for (let j = 0; j < hEnd; j++) { // by column
        G[i][j] = ' ';
    
        if (i === 0 && j === 0) { // top-left corner
          G[i][j] = '┌';
        } else if (i === 0 && j === hEnd - 1) { // top-right corner
          G[i][j] = '┐';
        } else if (i === vEnd - 1 && j === 0) { // bottom-left corner
          G[i][j] = '└';
        } else if (i === vEnd - 1 && j === hEnd - 1) { // bottom-right corner
          G[i][j] = '┘';
        } else if ((j % 3 === 0) && (i % vEnd !== 0 && i !== vEnd - 1 && i % 2 === 1)) {
          G[i][j] = '│';
        } else if (i % 2 === 0) {
          G[i][j] = '─';
        }
    
        if (m > 1) { // More than one column
          if (j % 3 === 0 && j !== 0 && j !== hEnd - 1 && i === 0) {
            G[i][j] = '┬';
          }
          if (j % 3 === 0 && j !== 0 && j !== hEnd - 1 && i === vEnd - 1) {
            G[i][j] = '┴';
          }
        }
    
        if (n > 1) { // More than one row
          if (i % 2 === 0 && i !== 0 && i !== vEnd - 1 && j === 0) {
            G[i][j] = '├';
          }
          if (i % 2 === 0 && i !== 0 && i !== vEnd - 1 && j === hEnd - 1) {
            G[i][j] = '┤';
          }
        }
    
        if (n > 1 && m > 1) { // More than one row and column
          if (i % 2 === 0 && j % 3 === 0 && i !== 0 && j !== 0 && i !== vEnd - 1 && j !== hEnd - 1) {
            G[i][j] = '┼';
          }
        }
      }
    }
    
    function buildMaze() {
      const mySet = new disjointSet();
      const width = m;
      const height = n;
      let setSize = 0;
      const graph = [];
      const visitedMap = {};
      const walls = {};
      const rightWalls = [];
      const downWalls = [];
      let location = 0;
    
      mySet.addElements(width * height);
    
      console.log('initializing grid (all walls are up)');
      
      // init 'graph'
      // each room has two walls, a down and right wall.
      for (let i = 0; i < width; i++) {
        graph[i] = new Array(height);
        for (let j = 0; j < height; j++) {
          graph[i][j] = location;
    
          walls[location] = { down: true, right: true };
          visitedMap[location] = false;
    
          // If you can label the rooms with just 2 digits
          if (width * height < 100) {
            const locationString = location.toString();
    
            G[j * 2 + 1][i * 3 + 1] = locationString[0];
            G[j * 2 + 1][i * 3 + 2] = locationString[1];
    
          }
    
          rightWalls.push({ x: i, y: j });
          downWalls.push({ x: i, y: j });
          location++;
        }
      }
    
      console.log('shuffled the walls for random selection');
      
      // Randomly shuffle the walls
      shuffle(rightWalls);
      shuffle(downWalls);
    
      // Picking random walls to remove
      while (setSize !== mySet.elements - 1) {
        const randomWall = Math.floor((Math.random() * 2) + 1);
        if (randomWall === 1 && downWalls.length > 0) {
          // Down wall
          const currentRoom = downWalls.pop();
          const iX = currentRoom.x;
          const iY = currentRoom.y;
          const iYdown = iY + 1;
          if (iYdown < height) {
            const u = graph[iX][iY];
            const v = graph[iX][iYdown];
            
            if (mySet.find(u) !== mySet.find(v)) {
              
              console.log(`Rooms: ${u} & ${v} now belong to the same set, delete wall between them`);
    
              Tracer.delay();
              
              mySet.setUnion(u, v);
              setSize++;
              // delete wall
              walls[u].down = false;
            } else {
              
              console.log(`Rooms: ${u} & ${v} would create a cycle! This is not good!`);
              Tracer.delay();
              
            }
            
          }
        } else if (randomWall === 2 && rightWalls.length > 0) {
          // Right Wall
          const currentRoom = rightWalls.pop();
          const iX = currentRoom.x;
          const iY = currentRoom.y;
          const iXright = iX + 1;
          if (iXright < width) {
            const u = graph[iX][iY];
            const v = graph[iXright][iY];
            
            if (mySet.find(u) !== mySet.find(v)) {
              
              console.log(`Rooms: ${u} & ${v} now belong to the same set, delete wall between them`);
    
              Tracer.delay();
              
              mySet.setUnion(u, v);
              setSize++;
              // delete wall
              walls[u].right = false;
            } else {
              
              console.log(`Rooms: ${u} & ${v} would create a cycle! This is not good!`);
              Tracer.delay();
              
            }
            
          }
        }
      }
    
      console.log('deleting the walls');
      
      // update deleted walls
      for (let i = 0; i < width; i++) {
        for (let j = 0; j < height; j++) {
          const currentWall = walls[graph[i][j]];
    
          if (currentWall.down === false) {
            G[j * 2 + 2][i * 3 + 1] = ' ';
            G[j * 2 + 2][i * 3 + 2] = ' ';
            
          }
    
          if (currentWall.right === false) {
            G[j * 2 + 1][i * 3 + 3] = ' ';
            
          }
          
        }
      }
      
      console.log('cleaning up the grid!');
      
      cleanUpGrid(width, height);
    
      // Clear out walls for the start and end locations.
      const randomStart = Math.floor(Math.random() * width);
      const randomEnd = Math.floor(Math.random() * width);
    
      console.log('setting the Start (S) & End (E) locations');
    
      // Start Location
      G[0][randomStart * 3 + 1] = ' ';
      G[0][randomStart * 3 + 2] = ' ';
      G[1][randomStart * 3 + 1] = 'S';
    
      // End Location
      G[vEnd - 1][randomEnd * 3 + 1] = ' ';
      G[vEnd - 1][randomEnd * 3 + 2] = ' ';
      G[vEnd - 2][randomEnd * 3 + 1] = 'E';
    
      cleanUpStartLocation(randomStart);
      cleanUpEndLocation(randomEnd);
    
      console.log('maze is completed!');
    
      // set the data
      
    }
    
    function cleanUpStartLocation(start) {
      if (G[0][start * 3] === '┬' && G[1][start * 3] === '│') {
        G[0][start * 3] = '┐';
      }
      if (G[0][start * 3 + 3] === '┬' && G[1][start * 3 + 3] === '│') {
        G[0][start * 3 + 3] = '┌';
      }
      if (G[0][start * 3] === '┌') {
        G[0][start * 3] = '│';
      }
      if (G[0][start * 3 + 3] === '┐') {
        G[0][start * 3 + 3] = '│';
      }
    }
    
    function cleanUpEndLocation(end) {
      if (G[vEnd - 1][end * 3] === '┴' && G[vEnd - 2][end * 3] === '│') {
        G[vEnd - 1][end * 3] = '┘';
      }
      if (G[vEnd - 1][end * 3 + 3] === '┴' && G[vEnd - 2][end * 3 + 3] === '│') {
        G[vEnd - 1][end * 3 + 3] = '└';
      }
      if (G[vEnd - 1][end * 3] === '└') {
        G[vEnd - 1][end * 3] = '│';
      }
      if (G[vEnd - 1][end * 3 + 3] === '┘') {
        G[vEnd - 1][end * 3 + 3] = '│';
      }
    }
    
    function cleanUpGrid(width, height) {
      // Remove room numbers
      for (let i = 0; i < width; i++) {
        for (let j = 0; j < height; j++) {
          G[j * 2 + 1][i * 3 + 1] = ' ';
          G[j * 2 + 1][i * 3 + 2] = ' ';
        }
      }
    
      // clean up grid for looks
      for (let i = 0; i < vEnd; i++) {
        for (let j = 0; j < hEnd; j++) {
          if (G[i][j] === '├') {
            if (G[i][j + 1] === ' ') {
              G[i][j] = '│';
            }
          }
    
          if (G[i][j] === '┤') {
            if (G[i][j - 1] === ' ') {
              G[i][j] = '│';
            }
          }
    
          if (G[i][j] === '┬') {
            if (G[i + 1][j] === ' ') {
              G[i][j] = '─';
            }
          }
    
          if (G[i][j] === '┴') {
            if (G[i - 1][j] === ' ') {
              G[i][j] = '─';
            }
          }
    
          if (G[i][j] === '┼') {
            if (G[i][j + 1] === ' ' && G[i - 1][j] === ' ' && G[i][j - 1] !== ' ' && G[i + 1][j] !== ' ') {
              G[i][j] = '┐';
            } else if (G[i][j - 1] === ' ' && G[i - 1][j] === ' ' && G[i + 1][j] !== ' ' && G[i][j + 1] !== ' ') {
              G[i][j] = '┌';
            } else if (G[i][j - 1] === ' ' && G[i + 1][j] === ' ' && G[i - 1][j] !== ' ' && G[i][j + 1] !== ' ') {
              G[i][j] = '└';
            } else if (G[i][j + 1] === ' ' && G[i + 1][j] === ' ' && G[i - 1][j] !== ' ' && G[i][j - 1] !== ' ') {
              G[i][j] = '┘';
            } else if (G[i][j + 1] === ' ' && G[i][j - 1] === ' ' && (G[i + 1][j] === ' ' || G[i - 1][j] === ' ')) {
              G[i][j] = '│';
            } else if (G[i + 1][j] === ' ' && G[i - 1][j] === ' ' && (G[i][j - 1] === ' ' || G[i][j + 1] === ' ')) {
              G[i][j] = '─';
            } else if (G[i][j + 1] === ' ' && G[i][j - 1] === ' ') {
              G[i][j] = '│';
            } else if (G[i + 1][j] === ' ' && G[i - 1][j] === ' ') {
              G[i][j] = '─';
            } else if (G[i + 1][j] === ' ' && G[i - 1][j] !== ' ' && G[i][j - 1] !== ' ' && G[i][j + 1] !== ' ') {
              G[i][j] = '┴';
            } else if (G[i - 1][j] === ' ' && G[i + 1][j] !== ' ' && G[i][j + 1] !== ' ' && G[i][j - 1] !== ' ') {
              G[i][j] = '┬';
            } else if (G[i][j + 1] === ' ' && G[i - 1][j] !== ' ' && G[i + 1][j] !== ' ' && G[i][j - 1] !== ' ') {
              G[i][j] = '┤';
            } else if (G[i][j - 1] === ' ' && G[i - 1][j] !== ' ' && G[i + 1][j] !== ' ' && G[i][j + 1] !== ' ') {
              G[i][j] = '├';
            }
          }
        }
      }
    }
    
    class disjointSet {
      constructor() {
        this.set = [];
        this.elements = 0;
      }
    
      addElements(numberOfElements) {
        for (let i = 0; i < numberOfElements; i++) {
          this.elements++;
          this.set.push(-1);
        }
      }
    
      find(element) {
        if (this.set[element] < 0) {
          return element;
        }
        return this.set[element] = this.find(this.set[element]);
      }
    
      setUnion(_a, _b) {
        const a = this.find(_a);
        const b = this.find(_b);
    
        if (a !== b) {
          const newSize = (this.set[a] + this.set[b]);
          if (this.compareSize(a, b)) {
            this.set[b] = a;
            this.set[a] = newSize;
          } else {
            this.set[a] = b;
            this.set[b] = newSize;
          }
        }
      }
    
      compareSize(a, b) {
        if (this.set[a] === this.set[b]) {
          return true;
        } else if (this.set[a] < this.set[b]) {
          return true;
        }
        return false;
      }
    }
    
    // http://bost.ocks.org/mike/shuffle/
    function shuffle(array) {
      let m = array.length;
      let t;
      let i;
      // While there remain elements to shuffle…
      while (m) {
        // Pick a remaining element…
        i = Math.floor(Math.random() * m--);
        // And swap it with the current element.
        t = array[m];
        array[m] = array[i];
        array[i] = t;
      }
      return array;
    }
    
    buildMaze();