电子老鼠闯迷宫

SSLGZ-1455-电子老鼠闯迷宫/mouse.pas

题意:
12×12方格图,找出一条自入口(2,9)到出口(11,8)的最短路径。
这里写图片描述

解题思路:
用深搜,首先判断哪个方向能走,再判断有没有出界,统计走的路程,如果找到了目标点就直接输出从起点到这的路程。

const
  maxn=12;
  wayn=4;
  dx:array[1..wayn] of integer=(-1,0,1,0);
  dy:array[1..wayn] of integer=(0,1,0,-1);
var
  px,py,qx,qy,s,last:integer;
  a:array[0..maxn+1,0..maxn+1] of integer;
  father:array[1..maxn*maxn] of integer;
  state:array[1..maxn*maxn,1..2] of integer;
procedure init;
  var
    i,j,n:integer;
  begin
    readln(n);
    read(px,py);
    readln(qx,qy);
    for i:=1 to n do
      begin
        for j:=1 to n do
         read(a[i,j]);
        readln;
      end;
  end;
function check(x,y:integer):boolean;
  begin
    check:=true;
    if (x<1) or (x>12) or (y<1) or (y>12) then check:=false;
    if a[x,y]=1 then check:=false;
  end;
procedure print(x:integer);
  begin
    if x=0 then exit;
    inc(s);
    print(father[x]);
    if x<>last then write('(',state[x,1],',',state[x,2],')->')
               else writeln('(',state[x,1],',',state[x,2],')')
  end;
procedure bfs;
  var
    tail,head,k,i:integer;
  begin
     head:=0;tail:=1;state[1,1]:=px;state[1,2]:=py;
     father[1]:=0;
     repeat
       head:=head+1;
       for k:=1 to wayn do
         if check(state[head,1]+dx[k],state[head,2]+dy[k])
           then begin
                  tail:=tail+1;
                  father[tail]:=head;
                  state[tail,1]:=state[head,1]+dx[k];
                  state[tail,2]:=state[head,2]+dy[k];
                  a[state[tail,1],state[tail,2]]:=1;
                  if (state[tail,1]=qx) and (state[tail,2]=qy)
                    then begin
                           s:=0;
                           last:=tail;
                           print(tail);
                           writeln(s);
                           tail:=0;
                         end;
              end;
    until head>=tail;
  end;
begin
  init;
  bfs;
end.
  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值