洛谷P1141 01迷宫
来源:互联网 发布:dev c 怎么改语言 编辑:程序博客网 时间:2024/05/16 11:18
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.
0 0
- 洛谷P1141 01迷宫
- 洛谷P1141 01迷宫
- 洛谷 P1141 01迷宫
- 洛谷P1141 01迷宫
- 洛谷P1141 01迷宫
- 洛谷 P1141 01迷宫
- |洛谷|BFS|P1141 01迷宫
- 【搜索】洛谷 P1141 01迷宫
- 洛谷P1141 01迷宫 解题报告
- P1141 01迷宫题解
- P1141 01迷宫
- P1141 01迷宫
- P1141 01迷宫
- P1141 01迷宫
- Luogu P1141 01迷宫
- 【p1141-01迷宫】解题记录
- [luogu]P1141 01迷宫-宽搜
- (洛谷)【P1141】01迷宫 [广度搜索][高性能]
- VSCode 快捷键 Windows版
- SqlServer 处理百万级以上的数据提高查询速度的方法
- 资源占用过高调试步骤
- 2016/01/19 - CRM论坛学习心得
- Java基本概念-xml相关
- 洛谷P1141 01迷宫
- ios 应用闪退原因
- Android drawable微技巧,你所不知道的drawable的那些细节
- codeforces 758D-D - Ability To Convert 数学细节题
- 小程序 用css实现遮罩效果
- c++ primer 学习笔记(一)
- 关于 procedure of object
- 【高可用架构】异地多活设计辣么难?其实是你想多了!
- freeMark入门使用,遇到比较多的问题