www.pudn.com > TJU.rar > ac1051.pas


program tju1051; 
const 
  maxsize=200; 
  dx:array[1..4]of shortint=(0,0,-1,1); 
  dy:array[1..4]of shortint=(-1,1,0,0); 
var 
  map:array[0..maxsize+1,0..maxsize+1]of char; 
  qx,qy:array[1..sqr(maxsize)*2]of byte; 
  dist:array[1..maxsize,1..maxsize]of longint; 
  n,m,i,j,f,r,x,y,d:longint; 
  found:boolean; 
begin 
  repeat 
    readln(n,m); 
    for i:=0 to n+1 do begin 
      map[i,0]:='#';map[i,m+1]:='#'; 
    end; 
    for i:=1 to m do begin 
      map[0,i]:='#';map[n+1,i]:='#'; 
    end; 
    for i:=1 to n do begin 
      for j:=1 to m do begin 
        read(map[i,j]); 
        if map[i,j]='a' then begin 
          f:=0;r:=1;qx[1]:=i;qy[1]:=j;dist[i,j]:=0; 
        end 
        else 
          dist[i,j]:=maxlongint; 
      end; 
      readln; 
    end; 
 
    found:=false; 
    repeat 
      inc(f);x:=qx[f];y:=qy[f]; 
      if map[x,y]='x' then begin 
        inc(r);qx[r]:=x;qy[r]:=y;inc(dist[x,y]);map[x,y]:='.'; 
      end 
      else 
        for d:=1 to 4 do begin 
          i:=x+dx[d];j:=y+dy[d]; 
          if (map[i,j]<>'#') and (dist[i,j]=maxlongint) then begin 
            inc(r);qx[r]:=i;qy[r]:=j;dist[i,j]:=dist[x,y]+1; 
            if map[i,j]='r' then begin found:=true;break;end; 
          end; 
        end; 
    until found or (f=r); 
    if found then writeln(dist[i,j]) else writeln('Poor ANGEL has to stay in the prison all his life.'); 
  until seekeof; 
end.