
修改一下之前程式,可以處理任何長方形迷宮。
(* 將圖形檔轉成適當尺寸 *)
mazepic = Import["http://tinyurl.com/8q7yw6p"];
test=Image[Binarize[ImageResize[mazepic,{6010,4010}]]];
(* 將圖形檔轉維正方形迷宮資料陣列 *)
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}];
mazedim=Dimensions@maze;
maze=If[mazedim[[1]]==mazedim[[2]],maze,
If[mazedim[[1]]>mazedim[[2]],
Flatten[{maze[[#]],Table[1,{mazedim[[1]]-mazedim[[2]]}]}]&/@Range[mazedim[[1]]],
Flatten[{Table[1,{mazedim[[2]]-mazedim[[1]]},{mazedim[[2]]}],maze},1]]];
mazeplot=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,601*402,601*401+1];
(* 轉換回原始迷宮座標 *)
data={If[Mod[#,wh[[1]]]==0,wh[[1]],Mod[#,wh[[1]]]],1+Quotient[#-0.001,wh[[1]]]}&/@mpath;
tmaze=Transpose@maze;
(* 標示最佳路徑 *)
(tmaze[[#[[1]],#[[2]]]]=Red)&/@({wh[[1]]+1-#[[1]],#[[2]]}&/@data);
(* 製作迷宮*)
ArrayPlot[If[mazedim[[1]]==mazedim[[2]],Transpose@tmaze,
If[mazedim[[1]]>mazedim[[2]],(Transpose@tmaze)[[All,mazedim[[2]]-mazedim[[1]]+1;;-1]],
(Transpose@tmaze)[[mazedim[[2]]-mazedim[[1]]+1;;-1]]]
]]

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