zoukankan      html  css  js  c++  java
  • SSL JudgeOnline 2278——Oliver的救援

    Description

    在你的帮助下,Oliver终于追到小X了,可有一天,坏人把小X抓走了。这正是Oliver英雄救美的时候。所以,Oliver又找到哆啦A梦,借了一个机器,机器显示出一幅方格地图,它告诉Oliver哪里能走,哪里不能走,。并且Oliver在这个地图的右下角,而小X在左上角。时间紧急,Oliver想知道,最少要走多少个格子,才能找到小X。(只能直走)。

    Input

    共N+1行,第一行为N,以下N行N列0-1矩阵,1表示不能通过,0表示可以通过(左上角和右下角为0). N<30.

    Output

    共一个数,为最少的走的格子数.

    Sample Input

    5
    01111
    00111
    10001
    11101
    11100

    Sample Output

    9


    这题跟“电子老鼠闯迷宫”类似

    我们每次向四个方向搜,广搜是如果搜到这个点就是最优的,一直搜知道找到小X。


    代码如下:

    const dx:array[1..4]of longint=(1,-1,0,0);
          dy:array[1..4]of longint=(0,0,1,-1);
    
    var  a:array[-1..2000,-1..2000]of char;
         n,b1,b2,e1,e2,l,tail:longint;
         state:array[1..1000000,1..2]of longint;
         father:array[1..2000000]of longint;
    
    procedure init;
    var i,j:longint;
    begin
      readln(n);
      for i:=1 to n do
        begin
          for j:=1 to n do read(a[i,j]);
          readln;
        end;
      readln(b1,b2,e1,e2);
    end;
    
    function check(x,y:longint):boolean;
    begin
      check:=true;
      if a[x,y]='1' then check:=false;
      if (x>n)or(y>n)or(y<1)or(x<1) then check:=false;
    end;
    
    procedure print(x:longint);
    begin
      if x=0 then exit;
      inc(l);
      print(father[x]);
    end;
    
    procedure bfs;
    var head,i:longint;
    begin
      head:=0; tail:=1; state[1,1]:=b1; state[1,2]:=b2; a[b1,b2]:='1';
      father[1]:=0;
      repeat
        inc(head);
        for i:=1 to 4 do
          if check(state[head,1]+dx[i],state[head,2]+dy[i]) then
            begin
              inc(tail);
              father[tail]:=head;
              state[tail,1]:=state[head,1]+dx[i];
              state[tail,2]:=state[head,2]+dy[i];
              a[state[tail,1],state[tail,2]]:='1';
              if (state[tail,1]=e1)and(state[tail,2]=e2) then
                begin
                  print(father[tail]);
                  tail:=0;
                  writeln(l);
                  halt;
                end;
            end;
      until head>=tail;
    end;
    
    begin
      init;
      bfs;
    end.
  • 相关阅读:
    html5+css3中的background: -moz-linear-gradient 用法 (转载)
    CentOS 安装Apache服务
    Linux 笔记
    CURL 笔记
    Spring Application Context文件没有提示功能解决方法
    LeetCode 389. Find the Difference
    LeetCode 104. Maximum Depth of Binary Tree
    LeetCode 520. Detect Capital
    LeetCode 448. Find All Numbers Disappeared in an Array
    LeetCode 136. Single Number
  • 原文地址:https://www.cnblogs.com/Comfortable/p/8412452.html
Copyright © 2011-2022 走看看