SSL JudgeOnlie 2324——细胞问题

Description

一矩形阵列由数字0到9组成,数字1到9代表细胞,细胞的定义为沿细胞数字上下左右还是细胞数字则为同一细胞,求给定矩形阵列的细胞个数。如:阵列
0234500067
1034560500
2045600671
0000000089
有4个细胞。

Input

输入共m+1行第一行有两个数据,分别表示总行数和总列数以下的m行,每行有n个0-9之间的数

Output

细胞个数

Sample Input

4
0234500067
1034560500
2045600671
0000000089
Sample Output

4


这也是一道广搜题

我们每一个点的搜。每一次细胞数加一,将与其相邻的细胞全部搜出来。最后我们就将细胞数输出。


代码如下:

const dx:array[1..4]of longint=(0,0,1,-1);
      dy:array[1..4]of longint=(1,-1,0,0);
var  total,n,m,i,j:longint;
     f:array[1..100,1..100]of boolean;
     state:array[1..100,1..100]of longint;
     s:string;

procedure bfs(p,q:longint);
var  head,tail,x,y,i:longint;
begin
  inc(total); f[p,q]:=false;
  head:=0; tail:=1; state[1,1]:=p; state[1,2]:=q;
  repeat
    inc(head);
    for i:=1 to 4 do
      begin
        x:=state[head,1]+dx[i];
        y:=state[head,2]+dy[i];
        if (x>0)and(x<=m)and(y>0)and(y<=n)and(f[x,y]=true) then
          begin
            inc(tail);
            state[tail,1]:=x;
            state[tail,2]:=y;
            f[x,y]:=false;
          end;
      end;
  until head>=tail;
end;

begin
  fillchar(f,sizeof(f),true);
  readln(m);
  for i:=1 to m do
    begin
      readln(s);
      n:=length(s);
      for j:=1 to n do if s[j]='0' then f[i,j]:=false;
    end;
  for i:=1 to m do
    for j:=1 to n do
      if f[i,j]=true then bfs(i,j);
  write(total);
end.
posted @ 2016-12-21 17:25  BEYang_Z  阅读(142)  评论(0编辑  收藏  举报