01迷宫
问题描述
有一个仅由数字0与1组成的n×n格迷宫。若你位于一格0上,那么你可以移动到相邻4格中的某一格1上,同样若你位于一格1上,那么你可以移动到相邻4格中的某一格0上。
你的任务是:对于给定的迷宫,询问从某一格开始能移动到多少个格子(包含自身)。
分析
bfs,对于每个连通的格子答案都是一样的,所以记录一下就不会超时。
时间复杂度
O(n)
代码
const
maxn=1000;
dx:array[1..4] of integer=(-1,0,1,0);
dy:array[1..4] of integer=(0,1,0,-1);
var
ans,f,a:array[0..maxn,0..maxn] of longint;
s:array[0..1000000,1..3] of longint;
st:ansistring;
i,j,n,m,qx,qy:longint;
function check(x,y:longint):boolean;
begin
check:=true;
if (x<1) or (x>n) or (y<1) or (y>n) then exit(false);
end;
procedure bfs(qx,qy:longint);
var
i,zx,zy,h,t:longint;
begin
s[1,1]:=qx;s[1,2]:=qy;
ans[qx,qy]:=1;
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) and (ans[zx,zy]=0) and (a[zx,zy]<>a[s[h,1],s[h,2]]) then
begin
inc(t);
s[t,1]:=zx;
s[t,2]:=zy;
ans[zx,zy]:=1;
end;
end;
end;
for i:=1 to t do
ans[s[i,1],s[i,2]]:=t;
end;
begin
readln(n,m);
for i:=1 to n do
begin
readln(st);
for j:=1 to n do
a[i,j]:=ord(st[j])-48;
end;
for i:=1 to n do
for j:=1 to n do
if ans[i,j]=0 then bfs(i,j);
for i:=1 to m do
begin
readln(qx,qy);
writeln(ans[qx,qy]);
end;
end.
maxn=1000;
dx:array[1..4] of integer=(-1,0,1,0);
dy:array[1..4] of integer=(0,1,0,-1);
var
ans,f,a:array[0..maxn,0..maxn] of longint;
s:array[0..1000000,1..3] of longint;
st:ansistring;
i,j,n,m,qx,qy:longint;
function check(x,y:longint):boolean;
begin
check:=true;
if (x<1) or (x>n) or (y<1) or (y>n) then exit(false);
end;
procedure bfs(qx,qy:longint);
var
i,zx,zy,h,t:longint;
begin
s[1,1]:=qx;s[1,2]:=qy;
ans[qx,qy]:=1;
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) and (ans[zx,zy]=0) and (a[zx,zy]<>a[s[h,1],s[h,2]]) then
begin
inc(t);
s[t,1]:=zx;
s[t,2]:=zy;
ans[zx,zy]:=1;
end;
end;
end;
for i:=1 to t do
ans[s[i,1],s[i,2]]:=t;
end;
begin
readln(n,m);
for i:=1 to n do
begin
readln(st);
for j:=1 to n do
a[i,j]:=ord(st[j])-48;
end;
for i:=1 to n do
for j:=1 to n do
if ans[i,j]=0 then bfs(i,j);
for i:=1 to m do
begin
readln(qx,qy);
writeln(ans[qx,qy]);
end;
end.