poj 3322 Bloxorz I

本文深入探讨了使用BFS算法解决搜索问题的实例,特别关注了方向常量的处理技巧,通过代码示例展示了如何有效优化算法性能。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

基础的BFS题目,但是发现自己好久没有做过搜索题了,这道题做的很不爽,尤其是方向常量的处理,完全抄袭了他人的。

代码:

const
  nx:array[0..2,1..4] of integer=((1,-2,0,0),(1,-1,0,0),(0,0,-1,2));
  ny:array[0..2,1..4] of integer=((0,0,1,-2),(0,0,-1,2),(1,-1,0,0));
  ns:array[0..2,1..4] of integer=((2,2,1,1),(1,1,0,0),(2,2,0,0));
type
  ji=record
  x,y,s,w:longint;
end;
var
  q:array[0..2000000] of ji;
  a:array[0..511,0..511] of char;
  v:array[0..511,0..511,0..2] of boolean;
  n,m,s,t,head,tail,now,w,x,y,i,j,k:longint;
  nt:ji;
  vv:boolean;

begin
readln(n,m);
while n<>0  do
begin
  for i:=0 to n+1 do
    for j:=0 to m+1 do
      a[i,j]:='#';
  vv:=false;
  t:=0;
  fillchar(v,sizeof(v),0);
  for i:=1 to n do
    begin
      for j:=1 to m do
        begin
          read(a[i,j]);
          if a[i,j]='O' then
            begin
              nt.x:=i;
              nt.y:=j;
              nt.s:=0;
            end else
          if a[i,j]='X' then
            begin
              if t=0 then
                begin
                  q[1].x:=i;
                  q[1].y:=j;
                  q[1].s:=0;
                  x:=i;
                  y:=j;
                  t:=1;
                  v[x,y,0]:=true;
                  now:=1;
                end else
              begin
                v[x,y,0]:=false;
                if i=x then now:=1
                else now:=2;
                v[x,y,now]:=true;
                q[1].s:=now;
              end;
            end;
        end;
      readln;
    end;
  head:=1; tail:=1; q[1].w:=0;
  while head<=tail do
    begin
      x:=q[head].x; y:=q[head].y; now:=q[head].s; w:=q[head].w+1;
      for i:=1 to 4 do
        begin
          s:=q[head].x+nx[now,i];
          t:=q[head].y+ny[now,i];
          k:=ns[now,i];
          if (s<1)or(t<1)or(s>n)or(t>m) then continue;
          if a[s,t]='#' then continue;
          if (k=0)and(a[s,t]='E') then continue;
          if (k=1)and(a[s,t+1]='#') then continue;
          if (k=2)and(a[s+1,t]='#') then continue;
          if v[s,t,k] then continue;
          v[s,t,k]:=true;
          inc(tail);
          q[tail].x:=s; q[tail].y:=t; q[tail].s:=k; q[tail].w:=w;
          if (q[tail].x=nt.x)and(q[tail].y=nt.y)and(k=0) then
            begin
              writeln(w);
              vv:=true;
              break;
            end;
        end;
      if vv then break;
      inc(head);
    end;
  if not vv then writeln('Impossible');
  readln(n,m);
end;
end.

  

转载于:https://www.cnblogs.com/reflec94/archive/2011/10/20/2218437.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值