Advertisement
mgaikema

Mathematica Maze Generation

Jul 25th, 2017
86
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 1.14 KB | None | 0 0
  1. (* ::Package:: *)
  2.  
  3. (* ::Title:: *)
  4. (*Mazes*)
  5.  
  6.  
  7. (* Mazes in Mathematica: http://bit.ly/2tBFMnT *)
  8.  
  9.  
  10. (* Clear variables. *)
  11. ClearAll["Global`*"]
  12. (* Limit variable scope to just this document. *)
  13. SetOptions[EvaluationNotebook[], CellContext -> Notebook]
  14. (* Set the current directory as the working directory. *)
  15. SetDirectory[NotebookDirectory[]]
  16.  
  17.  
  18. (* custom styling *)
  19. style = {Background -> GrayLevel[0],
  20. BaseStyle -> {Directive[White, EdgeForm[], Opacity[1]]},
  21. VertexShapeFunction -> (Rectangle[#1 + .16, #1 - .16] &),
  22. EdgeShapeFunction -> (Rectangle[#1[[1]] + .16, #1[[2]] - .16] &)};
  23. embedding = GraphEmbedding[GridGraph[{20, 30}]];
  24.  
  25.  
  26. (* Create a graph with random edge weights. *)
  27. g = GridGraph[{20, 30}, EdgeWeight -> RandomReal[10, 1150]];
  28.  
  29.  
  30. (* Find the spanning tree of the graph containing the vertex 1. *)
  31. tree = FindSpanningTree[{g, 1}];
  32.  
  33.  
  34. (* Create the maze using the tree. *)
  35. maze = Graph[tree, VertexCoordinates -> embedding, style]
  36. Export["maze.png",maze]
  37.  
  38.  
  39. (* Highlight the shortest path from 1 to 20*30=600. *)
  40. HighlightGraph[maze, PathGraph[FindShortestPath[maze, 1, 600]]]
  41. Export["maze-solution.png",%]
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement