網頁

Tuesday 28 February 2012

1st Recursion

初學 PASCAL 時, 覺得 recursion 很難理解
當然現在知道 recursion 和 procedure call 原理都是一樣, 沒甚麼特別
(其實如果當年懂得 stack 的概念的話應該容易理解一點)
溫 342 procedure call 的時侯突然想起第一次寫 recursion, 便去找當年幼嫩的代碼

[PCOJ1057 Oil Deposits - Find #components in n*m grid]

var n, m, i, j, count : integer;
    v : array[0..105, 0..105] of boolean;
    s : array[0..105] of string;

procedure lab(x, y : integer);
var i, j : integer;
begin
   v[x, y] := true;
   for i:=-1 to 1 do
      for j:=-1 to 1 do begin
          if (x+i=0) or (x+i>n) or (y+j=0) or (y+j>m) then continue;
          if (v[x+i, y+j] = false) and (s[x+i, y+j] = '@')
          then lab(x+i,y+j);
      end;
end;

begin
   readln(n, m);
   for i:=1 to n do readln(s[i]);
   count := 0;

   for i:=1 to n do
       for j:=1 to m do
           if (v[i, j] = false) and (s[i,j] = '@') then begin
              lab(i, j);
              count := count+1;
           end;

   writeln(count);
end.

No comments:

Post a Comment