Maze generation: Difference between revisions

Content added Content deleted
Line 2,617: Line 2,617:
Here I generate a maze as a graph. Vertices of the graph are cells and edges of the graph are removed walls. This version is mush faster and is convenient to solve.
Here I generate a maze as a graph. Vertices of the graph are cells and edges of the graph are removed walls. This version is mush faster and is convenient to solve.
<lang mathematica>MazeGraph[m_, n_] :=
<lang mathematica>MazeGraph[m_, n_] :=
Block[{$RecursionLimit = Infinity, grid = GridGraph[{m, n}],
Block[{$RecursionLimit = Infinity, grid = GridGraph[{m, n}],
unvisitedQ}, unvisitedQ[_] := True;
visited = {}},
Graph[Range[m n], Reap[{AppendTo[visited, #];
Graph[Range[m n], Reap[{unvisitedQ[#] = False;
Do[
Do[
If[FreeQ[visited, neighbor],
If[unvisitedQ[neighbor],
Sow[# <-> neighbor]; #0@neighbor], {neighbor,
Sow[# <-> neighbor]; #0@neighbor], {neighbor,
RandomSample@AdjacencyList[grid, #]}]} &@
RandomSample@AdjacencyList[grid, #]}]} &@
RandomChoice@VertexList@grid][[2, 1]],
RandomChoice@VertexList@grid][[2, 1]],
GraphLayout -> {"GridEmbedding", "Dimension" -> {m, n}}]];
GraphLayout -> {"GridEmbedding", "Dimension" -> {m, n}}]];
maze = MazeGraph[13, 21]</lang>
maze = MazeGraph[13, 21]</lang>
{{Out}}
{{Out}}