-1

我试图从这个迷宫生成代码中取出所有已删除墙壁的数组。似乎无法让它工作,当我要求它打印时,它只会给我整个迷宫网格,而不是我要求的特定墙壁。

MazeGen2[m_, n_] := 
  Block[{$RecursionLimit = Infinity, 
    unvisited = Tuples[Range /@ {m, n}], maze, mazearray = {}, 
    mazeA},
   (*unvisited=Delete[unvisited,{{1},{2},{Length[
   unvisited]-1},{Length[unvisited]}}];*)
   (*Print[unvisited];*)

   maze = {{{{#, # - {0, 1}}, {#, # - {1, 0}}}} & /@ 
      unvisited, {{{0, n - 1}, {0, 0}, {m - 1, 
        0}}}};(*This generates the grid*)
   Print[maze];
   {unvisited = DeleteCases[unvisited, #];
      (*Print[unvisited];*)
      Do[
       If[MemberQ[unvisited, neighbor], 
        maze = DeleteCases[
          maze, {#, neighbor - {1, 1}} | {neighbor, # - {1, 1}}, {5}]
        (*mazeA=Flatten[AppendTo[mazearray,
        maze]];*)
        ; #0@neighbor],
       {neighbor, 
        RandomSample@{# + {0, 1}, # - {0, 1}, # + {1, 0}, # - {1, 
            0}}}
       ]
      } &@RandomChoice@unvisited;

   Flatten[maze]
   ];
4

1 回答 1

1

我在Rosetta Code网站上找到了您的代码,并且 - 非常感谢您!- 以下是如何使用基于图形的替代方法来生成迷宫。这是由用户 AlephAlpha 提供的:

MazeGraph[m_, n_] := 
Block[{$RecursionLimit = Infinity, grid = GridGraph[{m, n}], 
 visited = {}},
Graph[Range[m n],
 Reap[{AppendTo[visited, #];
     Do[
      If[FreeQ[visited, neighbor], 
       Sow[# <-> neighbor]; #0@neighbor],
      {neighbor, RandomSample@AdjacencyList[grid, #]}]} & @ 
   RandomChoice@VertexList@grid][[2, 1]], 
 GraphLayout -> {"GridEmbedding", "Dimension" -> {m, n}},
 EdgeStyle -> Directive[Opacity[1], AbsoluteThickness[12], Purple], 
 VertexShapeFunction -> None,
 VertexLabels -> "Name",
 VertexLabelStyle -> White,
 Background -> LightGray,
 ImageSize -> 300]];

 width = height = 8;

 maze = MazeGraph[width, height]

迷宫

既然迷宫是一个图表,解决方案就很容易了:

path = FindShortestPath[maze, 1, Last[VertexList[maze]]];
solution = Show[
  maze,
  HighlightGraph[
   maze,
   PathGraph[path],
   EdgeStyle -> Directive[AbsoluteThickness[5], White],
   GraphHighlightStyle -> None]
  ];

也很容易找到已删除的墙壁 - 在这里,它是GraphDifference原始GridGraph和迷宫之间的:

hg = HighlightGraph[
   GridGraph[{width, height}, 
    EdgeStyle -> 
     Directive[Opacity[0.2], Blue, AbsoluteThickness[1]]],
   EdgeList[GraphDifference[GridGraph[{width, height}], maze]],
   Background -> LightGray,
   ImageSize -> 300,
   GraphHighlightStyle -> {"Thick"}];

显示所有三个:

Row[{Labeled[maze, "maze"], Spacer[12], Labeled[hg, "deleted walls"], 
  Labeled[solution, "solution"]}]

在此处输入图像描述

为样式问题道歉 - 这是使用图表的难点...... :)

于 2013-07-14T11:01:58.620 回答