POJ2488 ——Dfs基础算法模板

Program poj2488;//By_Thispoet

Const 

	ddx:Array[1..8]of Integer=(-2,-2,-1,-1,1,1,2,2);

	ddy:Array[1..8]of Integer=(-1,1,-2,2,-2,2,-1,1);

	maxn=26;

Type

	rec=record

		ch:Char;

		num:Longint;

	end;

Var

	i,j,m,n,o,p,q			:Longint;

	v						:Array[1..maxn,1..maxn]of Boolean;

	stack					:Array[1..maxn*maxn]of rec;

	flag					:Boolean;

	

Procedure Printf();

begin

	for p:=1 to m*n do 

		write(stack[p].ch,stack[p].num);

	writeln;

end;

	

	

Function Check(i,j:Longint):Boolean;

begin

	if (i>n)or(i<=0)or(j>m)or(j<=0) then exit(false);

	exit(true);

end;

	

	

Procedure Dfs(code,i,j:Longint);

var k,p,q	:Longint;

begin

	if code=m*n then 

		begin

			Printf();

			flag:=true;

			exit;

		end;

	for k:=1 to 8 do 

		begin

			p:=i+ddx[k];q:=j+ddy[k];

			if check(p,q) and (not v[p,q]) then 

				begin	

					v[p,q]:=true;

					inc(code);

					stack[code].ch:=chr(p+64);

					stack[code].num:=q;

					Dfs(code,p,q);

					dec(code);

					if flag then exit;

					v[p,q]:=false;

				end;

		end;

end;

	

	

BEGIN



	readln(o);

	for q:=1 to o do 

		begin

			readln(m,n);

			writeln('Scenario #',q,':');

			flag:=false;

			fillchar(v,sizeof(v),0);

			for i:=1 to n do 

				begin

					for j:=1 to m do 

						begin

							stack[1].ch:=chr(i+64);

							stack[1].num:=j;

							v[i,j]:=true;

							Dfs(1,i,j);

							v[i,j]:=false;

							if flag then break;

						end;

					if flag then break;

				end;

			if not flag then 

				writeln('impossible');

			writeln;

		end;



END.

你可能感兴趣的:(poj)