網路抓下來的迷宮實在是太複雜了。想要用Mathematica找答案,還要輸入資料陣列,有點麻煩。所以寫了一個自動轉換的程式。
(* 將圖形檔轉成適當尺寸 *)
mazepic = Import["http://tinyurl.com/6qy6ffp"];
test=Image[Binarize[ImageResize[mazepic,{1010,1010}]]];
(* 將圖形檔轉成迷宮資料陣列 *)
temp=Map[Abs[#-1]&,ImageData[test],{1}];
maze=Map[If[Mean[Flatten[#[[4;;7,4;;7]]]]>0.47,1,0]&,
Partition[temp,{10,10}],{2}];
ArrayPlot[maze,FrameTicks->Automatic]
(* 迷宮維度 *)
wh=Dimensions@maze;
(* 建立迷宮通道資料 *)
n1=Table[If[maze[[i,j]]+maze[[i,j+1]]==0,
UndirectedEdge[wh[[1]]*(i-1)+j,wh[[1]]*(i-1)+j+1]],
{i,1,wh[[1]]},{j,1,wh[[2]]-1}];
n2=Table[If[maze[[i,j]]+maze[[i+1,j]]==0,
UndirectedEdge[wh[[1]]*(i-1)+j,wh[[1]]*i+j]],
{i,1,wh[[1]]-1},{j,1,wh[[2]]}];
medge=Union@Select[Flatten[{n1,n2}],Length@#>=2&];
(* 產生迷宮圖 *)
mg=Graph[Range[wh[[1]]*wh[[2]]],medge,
{FrameTicks->True,
VertexCoordinates->Flatten[Table[{i,j},{i,1,wh[[1]]},{j,1,wh[[2]]}],1]}]
(* 計算走出迷宮的最短路徑 *)
mpath=FindShortestPath[mg,101*10,101^2-9];
HighlightGraph[mg,PathGraph@FindShortestPath[mg,101*10,101^2-9]]
(* {313,313}的迷宮 *)
mazepic=
Import["http://www.unikatissima.de/uploads/unikatissima_maze_7qB.png"];
test=Image[Binarize[ImageResize[mazepic,{3130,3130}]]];
(*將圖形檔轉成迷宮資料陣列*)
temp=Map[Abs[#-1]&,ImageData[test],{1}];
maze=Map[If[Mean[Flatten[#[[4;;7,4;;7]]]]>0.47,1,0]&,
Partition[temp,{10,10}],{2}];
ArrayPlot[maze,FrameTicks->Automatic]


讀者回應 ( 0 意見 )
訂閱發佈留言 (Atom)
發佈留言
Please leave your name and tell me what you thought about this site. Comments, suggestions and views are welcomed.
如果這篇文章對你有幫助,那請留個訊息給我~