这题目其实是一道典型的bfs解迷宫问题,唯一的难度在于可以使用魔法,而且只能使用一次。因此我们需要多建立一张表存使用魔法后的情况。
代码:
const z:array[1..4,1..2]of -1..1=((1,0),(-1,0),(0,1),(0,-1));//四个方向
var i,j,k:longint;
m,n:longint;
h,t:longint; //第二张表为0,原表为1
a:array[0..1001,0..1001,0..1]of boolean;
x,y,u,p:array[0..2000001]of longint;
d,r:longint;
ch:char;
begin
readln(m,n,d,r);
for i:=1 to m do
begin
for j:=1 to n do
begin
read(ch);
if ch='.' then
begin
a[i,j,0]:=true;
a[i,j,1]:=true;
end
else
begin
a[i,j,0]:=false;
a[i,j,1]:=false;
end;
end;
readln;
end;
p[1]:=1;
x[1]:=1;
y[1]:=1;
u[1]:=0;
h:=1;
t:=1;
repeat
if (x[t]=m) and (y[t]=n) then//到终点时,输出
begin
write(u[t]);
exit;
end;
for i:=1 to 4 do//正常搜索,模板
if a[x[t]+z[i,1],y[t]+z[i,2],p[t]] then
begin
a[x[t]+z[i,1],y[t]+z[i,2],p[t]]:=false;
inc(h);
p[h]:=p[t];//保留之前是否使用魔法
x[h]:=x[t]+z[i,1];
y[h]:=y[t]+z[i,2];
u[h]:=u[t]+1;
end;
if p[t]=1 then//之前没有使用过魔法
begin
if (x[t]+d>0) and (y[t]+r>0) and (x[t]+d<=m) and (y[t]+r<=n) then//因为使用魔法可能会超过边界,所以要特判一下
if a[x[t]+d,y[t]+r,0] then//处理方法与正常相同
begin
inc(h);
a[x[t]+d,y[t]+r,0]:=false;
x[h]:=x[t]+d;
y[h]:=y[t]+r;
u[h]:=u[t]+1;
p[h]:=0;//记录为用过魔法
end;
end;
inc(t);
until t>h;
write(-1);//无解
end.