2013-07-11 38 views
-1

我想從這個迷宮代生成所有刪除牆的數組。似乎無法讓它工作,當我問它打印它只會給我整個迷宮網格,而不是我要求的具體牆壁。如何從迷宮生成代碼中獲取已刪除牆的數組Mathematica

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]];*) 
     ; #[email protected]], 
     {neighbor, 
     [email protected]{# + {0, 1}, # - {0, 1}, # + {1, 0}, # - {1, 
      0}}} 
     ] 
     } &@[email protected]; 

    Flatten[maze] 
    ]; 
+1

我太懶惰剪切和粘貼一個包含註釋掉代碼的代碼片段,它們的存在會讓您的函數更難理解。 –

+1

我懶得讀@HighPerformanceMark的評論 –

+0

我建議你(嘗試)編寫代碼來繪製你的迷宮。你會發現你的初始網格被糾纏起來。 – agentp

回答

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]; #[email protected]], 
     {neighbor, [email protected][grid, #]}]} & @ 
    [email protected]@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] 

maze

解決方案現在很容易的迷宮圖:

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

而且也容易爲找到刪除的牆壁 - 在這裏,這是原始GridGraph與迷宮之間的GraphDifference

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"]}] 

enter image description here

道歉的樣式問題 - 這是用圖表的最困難的部分... :)

+0

不應該在牆壁之間的路徑? (只是與rosetta代碼版本比較).. – agentp

+0

@george,因爲我看到它,牆壁是灰色的,走廊是紫色的,解決方案是白色的。所以刪除的牆壁實際上是刪除走廊.. :) – cormullion

+0

+尋找來源.. – agentp