Title
电子老鼠走迷宫
Description
如下图12×12方格图,找出一条自入口(2,9)到出口(11,8)的最短路径。
Input
Output
Sample Input
12 //迷宫大小 2 9 11 8 //起点和终点 1 1 1 1 1 1 1 1 1 1 1 1 //邻接矩阵,0表示通,1表示不通 1 0 0 0 0 0 0 1 0 1 1 1 1 0 1 0 1 1 0 0 0 0 0 1 1 0 1 0 1 1 0 1 1 1 0 1 1 0 1 0 0 0 0 0 1 0 0 1 1 0 1 0 1 1 1 1 1 1 1 1 1 0 0 0 1 0 1 0 0 0 0 1 1 0 1 1 1 0 0 0 1 1 1 1 1 0 0 0 0 0 1 0 0 0 0 1 1 1 1 0 1 1 1 1 0 1 0 1 1 1 1 1 1 1 1 0 0 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1
Sample Output
(2,9)->(3,9)->(3,8)->(3,7)->(4,7)->(5,7)->(5,6)->(5,5)->(5,4)->(6,4)->(7,4)->(7,3)->(7,2)->(8,2)->(9,2)->(9,3)->(9,4)->(9,5)->(9,6)->(8,6)->(8,7)->(8,8)->(9,8)->(9,9)->(10,9)->(11,9)->(11,8) 27
思路:
这题是一道经典的广搜,一层一层的搜下去,可以再走的过程中把每个节点的父节点记录下来,这样最后就可以逆着输出。
程序如下:
var i,j,k,x,y,px,py,qx,qy,s,last:longint; a:array [0..13,0..13] of longint; father:array [0..10000] of longint; state:array [0..10000,1..3]of longint; dx:array [1..4,1..2] of longint; procedure print(x:longint); begin if x=0 then exit; inc(s); print(father[x]); if x<>last then write('(',state[x,1],',',state[x,2],')->') else writeln('(',state[x,1],',',state[x,2],')'); end; procedure work; var head,tail,i,wayn:longint; begin head:=0;tail:=1;state[1,1]:=px;state[1,2]:=py; father[1]:=0; repeat inc(head); for wayn:=1 to 4 do begin x:=state[head,1]+dx[wayn,1]; y:=state[head,2]+dx[wayn,2]; if (x<=i)and(x>=1)and(y<=i)and(y>=1)and(a[x,y]=0) then begin inc(tail); father[tail]:=head; state[tail,1]:=state[head,1]+dx[wayn,1]; state[tail,2]:=state[head,2]+dx[wayn,2]; a[state[tail,1],state[tail,2]]:=1; if (state[tail,1]=qx)and(state[tail,2]=qy) then begin s:=0; last:=tail; print(tail); writeln(s); tail:=0; end; end; end; until head>=tail; end; begin dx[1,1]:=1;dx[1,2]:=0; dx[2,1]:=0;dx[2,2]:=-1; dx[3,1]:=-1;dx[3,2]:=0; dx[4,1]:=0;dx[4,2]:=1; readln(i); read(px,py,qx,qy); for j:=1 to i do for k:=1 to i do read(a[j,k]); work; end.