【题目描述】
有一个N*N的房间,房间内有一些开关可以打开另外一些房间的灯。小强可以走向相邻的四个房间,但是小强非常怕黑,只有相邻的房间的灯是打开的,才敢进入。小强一开始身处[1,1]房间 ,问小强最多可以进入多少个房间。
【输入格式】
第一行,两个整数N和M
以下M行,每行四个整数x、y、a、b,表示在房间[x,y]可以打开房间[a,b]的灯
【输出格式】
最多可以进入多少个房间
【样例输入】
3 6
1 1 1 2
2 1 2 2
1 1 1 3
2 3 3 1
1 3 1 2
1 3 2 1
【样例输出】
5
【数据范围】
1≤N≤100
1≤M≤20000
【分析】
搜索,每次向四个方向扩展直到无法更新答案。
const
dx:array[1..4]of -1..1=(-1,1,0,0);
dy:array[1..4]of -1..1=(0,0,-1,1);
var
a,b,c,d:array[0..20001]of longint;
i,j,n,m,ans:longint;
flag:boolean;
x,y:array[0..101,0..101]of 0..1;
procedure swap(var x,y:longint);
var tmp:longint;
begin
tmp:=x;x:=y;y:=tmp;
end;
procedure qsort(l,r:longint);
var
i,j,mid:longint;
begin
i:=l;j:=r;
mid:=(l+r) div 2;
repeat
while (a[i]<a[mid]) or ((a[i]=a[mid])and(b[i]<b[mid])) or ((a[i]=a[mid])and(b[i]=b[mid])and(c[i]<c[mid])) or ((a[i]=a[mid])and(b[i]=b[mid])and(c[i]=c[mid])and(d[i]<d[mid])) do inc(i);
while (a[j]>a[mid]) or ((a[j]=a[mid])and(b[j]>b[mid])) or ((a[j]=a[mid])and(b[j]=b[mid])and(c[j]>c[mid])) or ((a[j]=a[mid])and(b[j]=b[mid])and(c[j]=c[mid])and(d[j]>d[mid])) do dec(j);
if i<=j then begin
swap(a[i],a[j]);swap(b[i],b[j]);swap(c[i],c[j]);swap(d[i],d[j]);
inc(i);dec(j);
end;
until i>j;
if l<j then qsort(l,j);
if i<r then qsort(i,r);
end;
procedure search(tx,ty:longint);
var
i,cx,cy:longint;
begin
y[tx,ty]:=1;
for i:=1 to 4 do begin
cx:=tx+dx[i]; cy:=ty+dy[i];
if (y[cx,cy]=0)and(x[cx,cy]=1)and(cx>=1)and(cx<=n)and(cy>=1)and(cy<=n) then search(cx,cy);
end;
end;
begin
read(n,m);
for i:=1 to m do read(a[i],b[i],c[i],d[i]);
qsort(1,m);
x[1,1]:=1;
y[1,1]:=1;
flag:=true;
while flag do begin
flag:=false;
for i:=1 to m do begin
if (x[a[i],b[i]]=1)and(y[a[i],b[i]]=1) then begin
if x[c[i],d[i]]=0 then flag:=true;
x[c[i],d[i]]:=1;
end;
if (x[a[i],b[i]]=1)and(y[a[i],b[i]]=1) then
for j:=1 to 4 do y[a[i]+dx[j],b[i]+dy[j]]:=1;
if (x[c[i],d[i]]=1)and(y[c[i],d[i]]=1) then
for j:=1 to 4 do y[c[i]+dx[j],d[i]+dy[j]]:=1;
end;
end;
fillchar(y,sizeof(y),0);
search(1,1);
ans:=0;
for i:=1 to n do
for j:=1 to n do
if y[i,j]=1 then inc(ans);
write(ans);
end.