弱弱的搜索题,
我的做法是将矩阵看做二进制然后用位运算来做的,感觉比较舒服
1 const dx:array[1..4] of integer=(-1,1,0,0); 2 dy:array[1..4] of integer=(0,0,-1,1); 3 4 type node=record 5 po,next:longint; 6 end; 7 8 var a:array[0..10010] of node; 9 d,q:array[0..70010] of longint; 10 p:array[0..20] of longint; 11 num:array[0..10,0..10] of longint; 12 i,j,n,k,m,st,en,len,x,y:longint; 13 s:string; 14 15 procedure add(x,y:longint); 16 begin 17 inc(len); 18 a[len].po:=y; 19 a[len].next:=p[x]; 20 p[x]:=len; 21 end; 22 23 procedure bfs; 24 var u,j,i,k,x,y,f,r:longint; 25 begin 26 f:=1; 27 r:=1; 28 q[1]:=st; 29 fillchar(d,sizeof(d),255); 30 d[st]:=0; 31 while f<=r do 32 begin 33 x:=q[f]; 34 k:=1; 35 for i:=0 to 15 do 36 begin 37 if k and x<>0 then 38 begin 39 j:=p[i]; 40 while j<>-1 do 41 begin 42 u:=1 shl a[j].po; 43 y:=(x xor k) or u; 44 if (x and u=0) and (d[y]=-1) then 45 begin 46 d[y]:=d[x]+1; 47 if y=en then exit; 48 inc(r); 49 q[r]:=y; 50 end; 51 j:=a[j].next; 52 end; 53 end; 54 k:=k shl 1; 55 end; 56 inc(f); 57 end; 58 end; 59 60 begin 61 fillchar(num,sizeof(num),255); 62 fillchar(p,sizeof(p),255); 63 for i:=1 to 4 do 64 begin 65 readln(s); 66 for j:=1 to 4 do 67 begin 68 num[i,j]:=k; 69 st:=st+(ord(s[j])-48)*(1 shl k); 70 inc(k); 71 end; 72 end; 73 readln; 74 for i:=1 to 4 do 75 begin 76 readln(s); 77 for j:=1 to 4 do 78 en:=en+(ord(s[j])-48)*(1 shl num[i,j]); 79 end; 80 for i:=1 to 4 do 81 for j:=1 to 4 do 82 for k:=1 to 4 do 83 begin 84 x:=i+dx[k]; 85 y:=j+dy[k]; 86 if num[x,y]<>-1 then add(num[i,j],num[x,y]); 87 end; 88 bfs; 89 writeln(d[en]); 90 end.