POJ1915 —— 双向广搜代码模板

Program poj1915;//By_Thispoet
Const
	maxn=100000;
	ddx:Array[1..8]of Integer=(1,1,2,2,-1,-1,-2,-2);
	ddy:Array[1..8]of Integer=(2,-2,1,-1,2,-2,1,-1);
Var
	i,j,k,m,n,p,q				:Longint;
	h,t							:Array[1..2]of Longint;
	step						:Array[1..2,0..300,0..300]of Longint;
	v							:Array[1..2,0..300,0..300]of Boolean;
	seq							:Array[1..2,1..maxn]of record x,y:Integer;end;
	flag						:Boolean;

Function Check(i,j:Longint):Boolean;
begin
	if (i>m)or(j>m)or(i<0)or(j<0)then exit(false);
	exit(true);
end;


Procedure Expand(code:Longint);
begin
	inc(h[code]);
	i:=seq[code,h[code]].x;
	j:=seq[code,h[code]].y;
	for k:=1 to 8 do
		begin
			p:=i+ddx[k];q:=j+ddy[k];
			if check(p,q) and not v[code,p,q] then
				begin
					inc(t[code]);
					seq[code,t[code]].x:=p;
					seq[code,t[code]].y:=q;
					v[code,p,q]:=true;
					step[code,p,q]:=step[code,i,j]+1;
					if v[1,p,q] and v[2,p,q] then
						begin
							flag:=true;
							exit;
						end;
				end;
		end;
end;


BEGIN

	readln(n);
	while n>0 do
		begin
			readln(m);dec(m);
			readln(p,q);
			fillchar(v,sizeof(v),0);
			fillchar(step,sizeof(step),0);
			seq[1,1].x:=p;seq[1,1].y:=q;
			v[1,p,q]:=true;
			readln(p,q);
			seq[2,1].x:=p;seq[2,1].y:=q;
			v[2,p,q]:=true;
			if v[1,p,q] and v[2,p,q] then
				begin
					writeln(0);
					dec(n);
					continue;
				end;
			h[1]:=0;h[2]:=0;
			t[1]:=1;t[2]:=1;
			flag:=false;
			repeat
				if (t[1]>h[1])and((t[1]-h[1]h[2] then Expand(2);
				if flag then break;
			until (t[1]<=h[1])and(t[2]<=h[2]);
			if flag then writeln(step[1,p,q]+step[2,p,q]) else writeln(0);
			dec(n);
		end;

END.

转载于:https://www.cnblogs.com/Thispoet/archive/2011/10/08/2202307.html

你可能感兴趣的:(POJ1915 —— 双向广搜代码模板)