program bzoj1054;
type arr=array[1..16]of longint;
var x:array[1..4]of longint=(-4,4,-1,1);
y:array[1..16]of longint;
z:array[1..16]of longint;
hash:array[0..100000]of boolean;
que,step:array[0..100000]of longint;
er:array[0..16]of longint;
ans:longint;
function calc(p:longint):arr;
var s:arr;
i:longint;
begin
for i:=1 to 16 do
begin
s[i]:=p and 1;
p:=p shr 1;
end;
exit(s);
end;
function calc(p:arr):longint;
var s,i:longint;
begin
s:=0;
for i:=1 to 16 do
s:=s+er[i]*p[i];
exit(s);
end;
procedure bfs;
var l,r,stop,u,i,j,next:longint;
now:arr;
begin
fillchar(que,sizeof(que),0);
fillchar(hash,sizeof(hash),false);
l:=0;r:=1;
que[l]:=calc(y);
hash[que[l]]:=true;
step[l]:=0;
stop:=calc(z);
while l<>r do
begin
u:=que[l];
now:=calc(u);
if u=stop then
begin
ans:=step[l];
exit;
end;
for i:=1 to 16 do
if now[i]=1 then
for j:=1 to 4 do
if (i+x[j]>0)and(i+x[j]<17)and(now[i+x[j]]=0)
and(((i mod 4=1)and(x[j]<>-1))or((i mod 4=0)and(x[j]<>1))
or((i mod 4<>1)and(i mod 4<>0))) then
begin
now[i+x[j]]:=1;
now[i]:=0;
next:=calc(now);
if not hash[next] then
begin
hash[next]:=true;
que[r]:=next;
step[r]:=step[l]+1;
inc(r);
if next=stop then
begin
ans:=step[r-1];
exit;
end;
end;
now[i+x[j]]:=0;
now[i]:=1;
end;
inc(l);
end;
end;
procedure init;
var ch,s:string;
i:longint;
begin
s:='';
for i:=1 to 4 do
begin
readln(ch);
s:=s+ch;
end;
for i:=1 to 16 do
y[i]:=ord(s[i])-ord('0');
s:='';
readln;
for i:=1 to 4 do
begin
readln(ch);
s:=s+ch;
end;
for i:=1 to 16 do
z[i]:=ord(s[i])-ord('0');
er[1]:=1;
for i:=2 to 16 do
er[i]:=er[i-1]*2;
ans:=-1;
bfs;
write(ans);
end;
begin
init;
end.
评论