一矩形阵列由数字0到9组成,数字1到9代表细胞,细胞的定义为沿细胞数字上下左右还是细胞数字则为同一细胞,求给定矩形阵列的细胞个数。
如:阵列
0234500067
1034560500
2045600671
0000000089
有4个细胞。
【输入】
输入共m+1行 (1<=m<=40, (1<=n<=40)
第一行有两个数据,分别表示总行数和总列数
以下的m行,每行有n个0-9之间的数
【输出】
细胞个数
【样例】
输入文件(cell.in)
4 10
0234500067
1034560500
2045600671
0000000089
输出文件(cell.out)
4程序1(真确的);
program cell276;
const
dx:array[1..4]of integer=(-1,0,1,0);
dy:array[1..4]of integer=(0,1,0,-1);
var
n,m,j,i,num,tot:integer;
map:array[1..100,1..10]of integer;
bl:array[1..100,1..100]of boolean;
pt:array[1..100,1..2]of integer;
s:string;
procedure init;
begin
assign(input,'input.txt');
assign(output,'output.txt');
reset(input);
rewrite(output);
end;
procedure bfs(p,q:integer);
var
i,hd,tl,x,y:integer;
begin
inc(num);
hd:=0; tl:=1; pt[tl,1]:=p; pt[tl,2]:=q;
bl[p,q]:=false;
repeat
inc(hd);
for i:=1 to 4 do
begin
x:=pt[hd,1]+dx[i];
y:=pt[hd,2]+dy[i];
if (x>0)and(x<=n) and (y>0)and(y<=m) and bl[x,y] then
begin
inc(tl);
pt[tl,1]:=x;
pt[tl,2]:=y;
bl[x,y]:=false;
end;
end;
until hd>=tl
end;
begin
init;
num:=0;
fillchar(bl,sizeof(bl),true);
readln(n,m);
for i:=1 to n do
begin
readln(s);
for j:=1 to m do
begin
map[i,j]:=ord(s[j])-ord('0');
if map[i,j]=0 then
begin
bl[i,j]:=false;
inc(tot);
end;
end;
end;
for i:=1 to n do
begin
for j:=1 to m do
if bl[i,j] then bfs(i,j);
end;
writeln(num);
close(input);
close(output);
end.
程序2(错误的输出)
program rq276;
const
dx:array[1..4]of -1..1=(-1,0,1,0);
dy:array[1..4]of -1..1=(0,1,0,-1);
var
i,j,m,n,tot:integer;
s:string;
bl:array[1..100,1..100]of boolean;
map:array[1..100,1..100]of integer;
qe:array[1..100,1..2]of integer;
procedure init;
begin
assign(input,'input.txt');
assign(output,'output.txt');
reset(input);
rewrite(output);
end;
procedure bfs(p,q:integer);
var
hd,tl,x,y,i:integer;
begin
inc(tot);
hd:=0; tl:=1;
qe[1,1]:=p; qe[1,2]:=q; bl[p,q]:=false;
repeat
inc(hd);
for i:=1 to 4 do
begin
x:=qe[hd,1]+dx[i];
y:=qe[hd,2]+dy[i];
if (x>0)and(x<=m) and (y>0)and(y<=n) and bl[x,y] then
begin
inc(tl);
qe[tl,1]:=x;
qe[tl,2]:=y;
bl[x,y]:=false;
end;
end;
until hd>=tl;
end;
begin
init;
tot:=0;
readln(m,n);
fillchar(bl,sizeof(bl),true);
for i:=1 to m do
begin
readln(s);
for j:=1 to n do
begin
map[i,j]:=ord(s[i])-ord('0');
if map[i,j]=0 then bl[i,j]:=false;
end;
end;
for i:=1 to m do
begin
for j:=1 to n do
if bl[i,j] then bfs(i,j);
end;
writeln(tot);
close(input);
close(output);
end.