Blazor Maze Solved

C# | Blazor | CSS-Grid

Searching for paths through randomly generated mazes in C# and Blazor. This builds on my previous article about how to randomly generate mazes and adds about 50 lines of code to do the solving. Press the button below 👇 to generate and solve a maze...

Depth first search

The code uses a recursive depth-first search algorithm to find a path through the maze. (Strangely, DFS was invented in the 19th century as a maze-solving technique long before computers came about).

The search code consists of a pair of mutually recursive functions. The primary function, Solve checks to see if we have reached the end square of the maze yet. If not, it checks to see if we can move left, down, right or up. If we can move, the first available direction is tried by making a call to the secondary recursive function. If moving in the chosen direction doesn't find a path that completes the maze, other available directions are tried.

Due to the recursiveness of the functions, each move direction is tried in full, down as long of a path as possible, before trying another move direction from the current square. This is what makes the search 'depth first'. The functions return true to each other when they have found a path to the end, otherwise they return false when no further progress can be made down a path.

Secondary function

The secondary function acts on the square we moved 'to'. It marks this square as visited. (Then it pauses for a bit for suspense, so that the maze isn't instantly solved). Then it makes a recursive call back to the first function to see if a successful move to the end can be made from this square. If so, true is returned and the current square is coloured the GOOD_PATH colour (dark purple) so that the good path through the maze is displayed.

Utilities

The only other code needed is some utilities to test if we can move to target squares. These have to check the maze bounds, check if walls are in the way, and check that the destination hasn't been visited already (in which case there is no point in visiting again, unless you like infinite recursion)

Finally...

Displaying and colouring the maze is a topic in itself. Tailwind and CSS-Grid make this easy, please see my previous post on generating and displaying the maze for more info.

That's about all there is to it. The full code is here.