填涂颜色
题目描述
由数字0
组成的方阵中,有一任意形状闭合圈,闭合圈由数字1构成,围圈时只走上下左右4个方向。现要求把闭合圈内的所有空间都填写成2.
分析
bfs:从四条边开始碰到0就向四个方向拓展,拓展到一个不为1的点就可以把这个点入队,队列中的所有点就是闭合圈外的点,输出时处理一下就可以啦。
时间复杂度
O(n)
代码
const
maxn=30;
dx:array[1..4] of longint=(-1,0,1,0);
dy:array[1..4] of longint=(0,1,0,-1);
var
a:array[0..maxn,0..maxn] of longint;
s:array[0..10000,1..3] of longint;
i,j,n:longint;
function check(x,y:longint):boolean;
begin
check:=true;
if (x<1) or (x>n) or (y<1) or (y>n) or (a[x,y]<>0) then exit(false);
end;
procedure bfs(qx,qy:longint);
var
i,h,t,zx,zy:longint;
begin
s[1,1]:=qx;s[1,2]:=qy;
s[1,3]:=maxlongint;
h:=0;t:=1;
while h<t do
begin
inc(h);
for i:=1 to 4 do
begin
zx:=s[h,1]+dx[i];
zy:=s[h,2]+dy[i];
if check(zx,zy) then
begin
inc(t);
s[t,1]:=zx;
s[t,2]:=zy;
a[zx,zy]:=maxlongint;
end;
end;
end;
end;
begin
readln(n);
for i:=1 to n do
for j:=1 to n do
read(a[i,j]);
for i:=1 to n do
begin
if a[1,i]=0 then bfs(1,i);
if a[i,1]=0 then bfs(i,1);
if a[n,i]=0 then bfs(n,i);
if a[i,n]=0 then bfs(i,n);
end;
for i:=1 to n do
begin
for j:=1 to n do
if a[i,j]=maxlongint
then write(0,' ')
else if a[i,j]=0 then write(2,' ') else write(a[i,j],' ');
writeln;
end;
end.