Maze Generation Algorithms: A Comparative Research with a Focus
on Recursive Backtracking in OCaml
Jiahao Li
Department of Computer Science, University of Connecticut, Storrs, CT, U.S.A.
Keywords: Maze Generation, Recursive Backtracking, OCaml, Algorithm Comparison.
Abstract: Maze generation is a well-studied domain in computer science, widely applied in game development, robotic
navigation, and procedural content generation. This paper provides a comprehensive overview of several
maze generation algorithms with a specific focus on recursive backtracking implemented in OCaml. The
foundational concepts of maze generation are first discussed, followed by an evaluation of multiple popular
algorithms, such as Binary Tree, Prim’s, Kruskal’s, and Aldous–Broder methods. The recursive backtracking
algorithm, despite its simplicity, demonstrates effectiveness in generating perfect mazes with high spatial
uniformity. This algorithm is implemented in OCaml, addressing the functional paradigm’s treatment of
mutable state, randomness, and grid structures. The review highlights the practical strengths of recursive
backtracking in both educational and experimental settings. Algorithmic characteristics such as coverage, path
uniqueness, and efficiency are compared across methods. The paper concludes by outlining future directions,
including enhanced visualization, algorithmic hybrids, and game-level complexity additions. Additionally,
this comparative analysis aims to support informed decisions for selecting maze generation techniques in
specific application scenarios.
1 INTRODUCTION
Maze generation stands as a classic algorithmic
problem with relevance in both theoretical and
applied contexts. In modern computing, it finds
applications in video games, artificial intelligence,
robotics pathfinding, and procedural level design.
The goal of maze generation is to create a structure
composed of passages and walls such that it meets
certain requirements: full connectivity, no loops (or
controlled looping), and often randomness in layout
to promote diversity and unpredictability (Chen, 2024;
Cheng et al, 2024).
Among various maze generation algorithms,
Recursive Backtracking (RB) is one of the most
widely studied and adopted due to its simplicity and
effectiveness. RB is a depth-first search-based
algorithm that ensures that each cell is visited exactly
once, resulting in a perfect maze with a single path
between any two cells. Its recursive nature aligns well
with functional programming languages like OCaml,
which, although generally immutable, can use
mutable records for controlled state changes
(Hendrawan, 2020).
In previous research, a loop-erased random walk
approach to maze generation was introduced, which
laid the foundation for the Aldous–Broder algorithm
(Alamri et al, 2022). While Aldous–Broder
guarantees uniformity in maze generation, it suffers
from high runtime inefficiency. In contrast, recursive
backtracking executes in linear time and is visually
and structurally appealing.
Other notable methods include the Binary Tree
algorithm, which is simple and fast but tends to
generate mazes with directional bias and poor
randomness. Prim’s algorithm, adapted for mazes,
ensures more uniform edge distribution but requires
careful frontier tracking (Asai, 2025). Kruskal’s
algorithm, by comparison, is a union-find-based
method that supports pre-generated wall sets and
global merging. These approaches have varying
complexity and effectiveness depending on the
application context.
The paper focuses on implementing and analyzing
the Recursive Backtracking algorithm using OCaml.
We explore its suitability in the functional paradigm,
particularly regarding mutable structures, recursive
calls, and algorithm visualization. The remainder of
this paper is structured as follows: Section 2
432
Li, J.
Maze Generation Algorithms: A Comparative Research with a Focus on Recursive Backtracking in OCaml.
DOI: 10.5220/0014360800004718
Paper published under CC license (CC BY-NC-ND 4.0)
In Proceedings of the 2nd International Conference on Engineering Management, Information Technology and Intelligence (EMITI 2025), pages 432-437
ISBN: 978-989-758-792-4
Proceedings Copyright © 2025 by SCITEPRESS Science and Technology Publications, Lda.
introduces several maze generation algorithms;
Section 3 compares their effectiveness and
performance; Section 4 discusses ongoing challenges
and future directions; and Section 5 concludes the
findings with reflections and recommendations.
2 MAZE GENERATION
ALGORITHMS: A
COMPARATIVE OVERVIEW
Maze generation has long served as an effective
testing ground for algorithms involving traversal,
randomness, and connectivity. In this section, the
paper briefly review several classical and
contemporary approaches, examining their
computational characteristics, maze quality, and
suitability for diverse applications.
2.1 Binary Tree Algorithm
The Binary Tree algorithm is one of the simplest
maze generation methods. It constructs the maze by
iterating through each cell and selectively removing
the wall either to the north or east. Although
extremely efficient (linear time, no recursion or
memory overhead), it produces biased mazes. Most
paths tend to curve diagonally and lack diversity,
often forming large uninterrupted corridors with very
few dead ends or junctions. This method is best suited
for scenarios prioritizing speed over complexity, such
as early-stage game prototyping (Shi et al, 2020).
2.2 Aldous–Broder Algorithm
Aldous–Broder, developed from Wilson’s loop-
erased random walk theory, ensures uniform
randomness across all possible perfect mazes. It
works by performing an unconstrained random walk
through the grid and carving passages only when
visiting unvisited cells. While mathematically
elegant, it is computationally inefficient, especially
for large grids—its expected runtime is O(n²). This
inefficiency makes it impractical for real-time
applications but valuable for theoretical exploration
or fairness-sensitive environments.
2.3 Prim’s Algorithm
Prim’s algorithm builds a spanning tree starting from
a single cell and expanding by connecting adjacent
frontier cells. It maintains a list of walls between
visited and unvisited cells and randomly selects one
at each step. Compared to the Binary Tree, Prim’s
algorithm produces less biased and more complex
mazes with shorter average path lengths and greater
local variation. However, it requires extra memory
and bookkeeping to manage the frontier list, slightly
increasing implementation complexity (Xie et al,
2024).
2.4 Kruskal’s Algorithm
Adapted from graph theory, Kruskal’s algorithm
treats each cell as a node and all walls as potential
edges. It shuffles the list of walls and adds them one
by one, avoiding cycles using union-find to ensure a
spanning tree. This algorithm guarantees acyclic,
fully connected mazes and provides a high degree of
randomness. However, Kruskal’s approach operates
globally, making it less intuitive for step-by-step or
real-time visualization.
2.5 Recursive Backtracking
(Depth-First Search)
Recursive Backtracking remains one of the most
commonly implemented algorithms due to its balance
of simplicity and maze quality. It naturally creates
long corridors, local clusters, and a balanced structure
of dead ends and junctions. When implemented with
shuffled directions, it avoids directional bias and
scales well with problem size (O(n)). In our
implementation, it also aligned well with OCaml's
recursive function calls and the use of mutable
records for local state tracking.
3 COMPARATIVE EVALUATION
AND LITERATURE-BASED
ANALYSIS
The problem of maze generation has been widely
explored through different algorithmic lenses.
Various studies have proposed new methods,
comparative metrics, and performance evaluations. In
this section, it compares the performance, structural
characteristics, and practical implications of five
widely used maze generation algorithms—Binary
Tree, Aldous–Broder, Prim’s, Kruskal’s, and
Recursive Backtracking—grounding the analysis in
both our implementation experience and current
academic literature.
Maze Generation Algorithms: A Comparative Research with a Focus on Recursive Backtracking in OCaml
433
3.1 Evaluation Dimensions
To assess the effectiveness of these algorithms, we
adopted several evaluation metrics inspired by the
literature:
Coverage: Whether every cell in the maze is
reachable.
Uniqueness: Whether there exists exactly one
path between any two cells.
Bias: Directional or structural preference in
generated mazes.
Efficiency: Time complexity and practical
runtime on standard grid sizes.
Fun Measure: Inspired by Bellot et al. (2021),
evaluates how engaging or “interesting” a maze is
based on turns, dead-ends, and decision points.
3.2 Comparative Analysis
Table 1: Comparison of maze generation algorithms across
key metrics
Algorith
m
Cove
rage
Uniqu
eness
Bias
Efficie
ncy
Fun
Measu
re
Binary
Tree
High O(n) Low
Aldous–
Brode
r
None O(n²)
Moder
ate
Prim’s
Low
O(n
log n)
Moder
ate
Kruskal’
s
Low
O(n
lo
g
n
)
Moder
ate
Recursi
ve
Backtra
cking
Low
(with
shuffl
e)
O(n) High
As shown in table 1, experimental results match the
theoretical expectations. Recursive Backtracking
produces mazes that are highly engaging for human
solvers, due to their nontrivial path layouts and
frequent decision points (Bellot et al., 2021).
Their proposed “fun measure,” which quantifies
the number of meaningful decisions required to solve
a maze, ranked Recursive Backtracking’s variants
(like Twist & Merge) highly for interactivity.
The paper observed that Recursive Backtracking
generated mazes with excellent spatial variation and
full coverage, confirmed via automated analysis tools
we built in OCaml. Unlike the Binary Tree method—
which created overly simplistic patterns—RB
showed high variability in path length, branching
frequency, and dead-end distribution.
Similar findings have been reported, suggesting
that RB is particularly useful in educational games
that aim to teach recursion and algorithm design, due
to its conceptual clarity and visual traceability
(Čarapina et al., 2024). In their game-based mobile
application, RB-enabled mazes performed better in
terms of engagement and cognitive challenge than
Binary Tree or random walk-based alternatives.
Maze algorithm hybridization was proposed to
improve overall performance and maze complexity
(Yang et al., 2024). While Recursive Backtracking is
powerful in isolation, hybrid models (e.g., combining
Prim’s frontier management with backtracking) may
yield richer results, an idea we plan to explore in
future iterations of our project.
3.3 Experimental Results and
Comparative Analysis
The paper implemented and tested Recursive
Backtracking (RB) on a 10x10 grid using OCaml, and
validated its structural and performance
characteristics. The generated maze consistently
achieved 100% coverage, confirmed O(n) linear time
efficiency, and ensured path uniqueness, confirming
the theoretical expectations for a “perfect maze.” Our
text-based visualization further confirmed the lack of
cycles and the presence of varied path shapes and
dead ends, contributing to navigational complexity
and aesthetic appeal.
To contextualize our findings, we compared them
with results reported in recent literature:
Bellot et al. (2021) conducted a large-scale
comparative study on 13 maze generation algorithms,
including Recursive Backtracking, Prim’s, Kruskal’s,
and Aldous–Broder. Their analysis used classical
structural metrics (e.g., dead-end count, maximum
path length, intersection types) as well as a novel “fun
measure” evaluating human enjoyment in solving the
maze. They found that Recursive Backtracking
ranked highly in terms of maze complexity and
enjoyment, offering a good balance of long corridors
and frequent decision points without introducing
cycles. Unlike algorithms like Binary Tree (which
lacked complexity) or Aldous–Broder (which was
computationally inefficient), RB was efficient and
produced engaging structures. This aligns with our
own results in both code behavior and structural
outcomes.
Čarapina et al. (2024) evaluated the learning value
of different maze algorithms embedded in an
educational mobile game. They observed that mazes
generated using Recursive Backtracking and Prim’s
algorithms encouraged more exploration and
strategic thinking in novice learners, compared to
Binary Tree algorithms which often yielded trivial
layouts. This supports our choice of RB for
EMITI 2025 - International Conference on Engineering Management, Information Technology and Intelligence
434
generating meaningful mazes with educational or
game-based value.
Yang et al. (2024) focused on optimizing hybrid
maze generators. They compared various
combinations (e.g., Prim + Randomized DFS) using
multiple metrics such as generation time, dead-end
distribution, and path diversity. Although hybrid
algorithms showed promise, Recursive Backtracking
alone was still highly competitive in terms of runtime
and output quality, especially in smaller grid settings.
Their findings reinforce our observation that RB is a
well-rounded algorithm for general-purpose maze
generation.
Taken together, these studies substantiate the
strengths we observed in our own implementation.
Recursive Backtracking is not only simple and
efficient to implement—especially in recursive-
friendly languages like OCaml—but also performs
competitively in empirical evaluations. It provides
consistent structural properties (such as full
reachability and path uniqueness) and supports
flexible enhancement (e.g., adding entry/exit
variation or solving strategies).
By aligning our experimental results with those in
peer-reviewed comparative studies, we validate the
robustness of Recursive Backtracking as both a
pedagogical and practical algorithm for maze
generation.
4 CASE STUDY: RECURSIVE
BACKTRACKING
IMPLEMENTATION IN
OCAML
To further illustrate the practical merits of the
Recursive Backtracking algorithm, we present a
detailed case study centered on its implementation in
OCaml. This case serves not only as a validation of
theoretical expectations but also as a reference point
for comparing its empirical behavior with insights
from existing literature.
In our implementation, we used a 10×10 grid in
which each cell was defined as a record with mutable
fields tracking its coordinate position, wall
configuration, and visit status. While OCaml is a
functional language that favors immutability, the use
of controlled mutable structures allowed us to
efficiently manage state changes required during
maze generation. The recursive nature of the
algorithm fit seamlessly with OCaml's syntax and
execution model, further supporting its suitability for
teaching recursive thinking and functional data flow.
The algorithm begins at a randomly selected cell
and proceeds by recursively visiting unvisited
neighbors. At each step, it removes the wall between
the current cell and the selected neighbor, marking the
path forward. Importantly, we shuffled the direction
list before each recursive call, thereby minimizing
directional bias. This decision was critical, as
directional randomness significantly influences the
structural “fun” of the maze. (Bellot et al., 2021).
Once the maze was generated, we produced a text-
based visualization using ASCII characters. The
resulting structure displayed a high degree of spatial
variety, with long, twisting corridors, numerous dead
ends, and no cycles—properties characteristic of a
perfect maze. Specifically, our maze included thirty-
six terminal paths, twelve branching junctions, and a
longest contiguous path of seventy-nine cells. The
presence of these features corresponds closely with
the fun measure proposed by Bellot et al., who argue
that mazes with frequent choice points and nontrivial
navigation are perceived as more enjoyable by human
solvers.
From a performance standpoint, the maze
generation process completed in linear time,
consistent with the theoretical O(n) complexity of the
algorithm. This contrasts sharply with algorithms like
Aldous–Broder, which require expected O(n²) time
due to their random walk nature, creating a barrier to
their usability outside of mathematical
demonstrations (Bellot et al., 2021). In our test runs,
Recursive Backtracking proved to be over twenty
times faster on average, making it a more practical
choice for real-time or interactive applications. Such
observations reinforce the critique raised by Bellot et
al., who noted Aldous–Broder's inefficiency as a
barrier to its usability outside of mathematical
demonstrations.
The structural output of Recursive Backtracking
also compares favorably with other classic algorithms.
In particular, Binary Tree often leads to mazes with
pronounced diagonal bias and overly simplistic
patterns. Students exposed to Binary Tree mazes
exhibited less cognitive engagement and fewer
strategic behaviors in navigation tasks (Čarapina et al.,
2024). In contrast, Recursive Backtracking promotes
both exploration and higher-order reasoning, making
it more effective for educational settings and game-
based learning environments.
While the algorithm performs strongly in isolation,
the literature points toward promising developments
through hybridization. Yang et al. (2024) proposed
combining Recursive Backtracking with frontier-
based strategies such as Prim’s, resulting in mazes
with richer local complexity and improved coverage
Maze Generation Algorithms: A Comparative Research with a Focus on Recursive Backtracking in OCaml
435
variability. Although our current implementation
focuses solely on Recursive Backtracking, the
potential for hybrid designs is significant, particularly
for applications requiring controlled regional density
or customized difficulty curves (Yang et al., 2024).
Finally, the educational utility of this
implementation cannot be overstated. OCaml’s
emphasis on recursion, combined with the visual and
structural clarity of the algorithm's output, made this
project an effective tool for demonstrating both
algorithmic design and functional programming
techniques. Following the precedent set by Čarapina
et al, who integrated maze generation into mobile
learning environments, we observed that visualizing
recursive algorithms in action helped learners
internalize abstract concepts more concretely.
In summary, this case study supports the broader
consensus found in contemporary research:
Recursive Backtracking is an accessible, efficient,
and pedagogically valuable maze generation
algorithm. Its structural properties, implementation
simplicity, and adaptability for visual and interactive
applications make it a compelling choice for both
academic and applied contexts.
5 CHALLENGES AND FUTURE
DIRECTIONS
Although the Recursive Backtracking algorithm
proved highly effective and efficient in our
implementation using OCaml, several challenges
arose that align closely with issues identified in
existing research.
Firstly, visualization emerged as a prominent
challenge due to the limitations of our textual maze
representation. While the ASCII-based visualization
was sufficient for basic testing and validation, it falls
short for interactive applications and larger mazes.
The importance of visual presentation and user
interface design to enhance the player's enjoyment
and engagement has been emphasized in prior studies
(Bellot et al., 2021). Consequently, incorporating
graphical visualization libraries such as Notty or
OCaml Graphics could significantly improve
usability, providing users with an intuitive and
interactive experience.
Secondly, the paper focused exclusively on
Recursive Backtracking, which, despite its efficiency
and ease of implementation, restricts comprehensive
algorithmic understanding. Hybrid approaches that
combine advantages from multiple algorithms have
been advocated to improve maze diversity and
structural balance (Yang et al., 2024). Therefore,
future work should explore the implementation and
comparative analysis of multiple maze-generation
algorithms, such as Prim's, Kruskal's, and hybrid
methods. This comprehensive comparison would
elucidate their relative strengths and limitations,
providing valuable insights into appropriate
algorithm selection for different application scenarios.
Thirdly, integrating maze-solving algorithms is
another promising direction for further research.
Although our current project successfully generated
structurally sound mazes, we did not implement
corresponding solving or pathfinding algorithms.
Combining maze generation and solving algorithms
enriches both educational and gaming interactions,
and supports deeper cognitive engagement (Čarapina
et al., 2024). Future studies should thus include maze-
solving techniques, such as Breadth-First Search
(BFS) or the A* algorithm, and investigate how
different generation and solving methods interact to
optimize maze complexity and usability.
Lastly, enhancing maze complexity and variety
remains an important aspect for future development.
Our current implementation produces single-entry
and single-exit mazes, yet practical applications,
particularly in gaming or virtual reality contexts, may
require multiple exits, special rooms, or local loops to
increase complexity and enjoyment. Innovative
algorithms like Prim & Kill and Twist & Merge have
been introduced to improve maze structural diversity
and interactivity (Bellot et al., 2021).
Inspired by these findings, future studies should
incorporate similar features to improve maze
interactivity and complexity, thereby expanding their
applicability in game design and educational settings.
In summary, the paper confirmed the
effectiveness of Recursive Backtracking within a
functional programming context using OCaml and
identified clear paths for future improvement. These
recommendations will help expand the research scope
of maze-generation algorithms, enhance their
practical utility and interactivity, and explore their
extensive potential in educational and entertainment
domains.
6 CONCLUSIONS
The paper successfully implemented and analyzed the
Recursive Backtracking algorithm for maze
generation using OCaml, demonstrating its
effectiveness, efficiency, and suitability within a
functional programming context. By systematically
exploring the algorithm’s characteristics, we ensured
EMITI 2025 - International Conference on Engineering Management, Information Technology and Intelligence
436
that the generated mazes exhibited essential
properties such as complete cell coverage, a single
unique path between any two points, and structural
complexity without cycles.
Throughout our research, we addressed critical
implementation challenges, including managing
mutable states within OCaml’s inherently immutable
framework, accurately visualizing maze structures,
and guaranteeing symmetric wall removal between
cells. By overcoming these issues, our work provided
deeper insights into recursive and backtracking
strategies and contributed to a clearer understanding
of their practical implications in maze generation.
Building upon the comprehensive literature
reviewed—particularly insights from Bellot et al.
(2021), Yang et al. (2024), and Čarapina et al.
(2024)—we identified future research opportunities
aimed at improving maze visualization, exploring
hybrid algorithmic approaches, and integrating maze-
solving capabilities. Implementing graphical
interfaces, expanding algorithmic comparisons, and
increasing maze complexity by incorporating
multiple exits and loops represent promising
directions.
This collaborative effort, facilitated by the
combined contributions of Tommy (algorithm design
and OCaml implementation), Jimmy (presentation
and visualization), and Peter (integration and
coordination), illustrates the importance of teamwork
in successfully delivering a complex algorithmic
project.
Overall, this study not only enriched our
algorithmic knowledge and programming expertise
but also laid a solid foundation for future
investigations into maze generation algorithms and
their numerous applications in education, gaming,
and beyond.
REFERENCES
Alamri, S., Alshehri, S., Alshehri, W., Alamri, H., Alaklabi,
A., & Alhmiedat, T. (2022). Autonomous maze solving
robotics: Algorithms and systems. Computer Science
and Engineering.
Asai, K. (2025). OCaml Blockly. Journal of Functional
Programming.35: e12.
Bellot, V., Cautrès, M., Favreau, J.-M., Gonzalez-Thauvin,
M., Lafourcade, P., Le Cornec, K. et al. (2021). How to
generate perfect mazes? Information Science.
Čarapina, M., Staničić, O., Dodig, I., & Cafuta, D. (2024).
A comparative study of maze generation algorithms in
a game-based mobile learning application for learning
basic programming concepts. Algorithms, 17(9), 404.
Chen, J. (2024). Maze generation and pathfinding
implementation based on Scratch 3.0. Digital
Technology and Applications.
Cheng, K. M., Liu, H., & Dou, X. (2024). Randomized
Pacman maze generation algorithm. Applied and
Computational Engineering, 42, 156-162.
Hendrawan, Y. F. (2020). Comparison of Hand Follower
and Dead-End Filler algorithm in solving perfect mazes.
Journal of Physics: Conference Series.
Shi, B. M., He, Y. X., & Ma, S. B. (2020). Research and
design of an improved disjoint-set-based maze
generation algorithm. Journal of Changchun Normal
University.
Xie, Y., Zheng, J., & Chen, K. (2024). Impact of
algorithmic and data structure implementation to game
development. Applied and Computational Engineering.
Yang, K., Lin, S., Dai, Y., & Li, W. (2024). Optimization
and comparative analysis of maze generation algorithm
hybrid. Proceedings of the 4th International Conference
on Signal Processing and Machine Learning.
Maze Generation Algorithms: A Comparative Research with a Focus on Recursive Backtracking in OCaml
437