数学491 323
取消评论
该过程从结束符(“ *”)开始,找到指向该结束符的箭头,依此类推,直到到达起点为止。
函数f [迷宫]。
(* positions of the arrowheads *)
aHeads[a_]:=Position[m,#]&/@{"^","v",">","<"}
(* position of the final labyrinth exit*)
final[a_]:=Position[a,"*"][[1]];
(* find arrowheads that point to the current location at {r,c} *)
aboveMe[{r_,c_},a_]:=Cases[aHeads[a][[2]],{r1_,c}/;r1<r]
belowMe[{r_,c_},a_]:=Cases[aHeads[a][[1]],{r1_,c}/;r1>r]
rightOfMe[{r_,c_},a_]:=Cases[aHeads[a][[4]],{r,c1_}/;c1>c]
leftOfMe[{r_,c_},a_]:=Cases[aHeads[a][[3]],{r,c1_}/;c1<c]
(*find the precursor arrowhead*)
precursor[{loc_,a_,list_:{}}]:=
(* end the search when the precursor has already been traversed or when there is no precursor *)
Which[MemberQ[list,loc],list,
loc=={},list,True,
(* otherwise find the next precursor *)
前体[{Flatten [{aboveMe [loc,a],belowMe [loc,a],rightOfMe [loc,a],leftOfMe [loc,a]},2],a,Prepend [list,loc]}]]]
(* return the path through the maze from start to finish *)
f[maze_]:= precursor[{final[maze[[1]]],maze[[1]]}]
打高尔夫球
f@z_:=Module[{p,h,m=z[[1]]},h@a_:=Position[a,#]&/@{"^","v",">","<","*"};
p[{v_,a_,j_:{}}]:=Module[{r,c,x=Cases},{r,c}=v;
Which[MemberQ[j,v],j,v=={},j,True,
p[{Flatten[{x[h[a][[2]],{r1_,c}/;r1<r],x[h[a][[1]],{r1_,c}/;r1>r],
x[h[a][[4]],{r,c1_}/;c1>c],x[h[a][[3]],{r,c1_}/;c1<c]},2],a,Prepend[j,v]}]]];
p[{Position[m,"*"][[1]],m}]]
例
迷宫。每个有序对都包含一个单元格的行和列。例如,{2,3}表示第2行第3列的单元格。
maze=Grid[Normal@ SparseArray[{{5, 5} -> "*",{1, 2} -> "v", {1, 5} -> "<",{2, 1} -> ">",
{2, 3} -> "v",{3, 3} -> ">", {3, 5} -> "^",{4, 1} -> ">", {4, 5} -> "v",{5, 1} -> "^",
{5, 2} -> "<",{_, _} -> " "}]]
输入值
f[maze]
输出:从开始到结束的路径。
{{2,1},{2,3},{3,3},{3,5},{1,5},{1,2},{5,2},{5,1},{ 4,1},{4,5},{5,5}}