P3818 小A和uim之大逃离 II

这题目其实是一道典型的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.
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值