主题:[原创]给新手做练习的读程序题目---BFS
const maxn=15;
type arraytype=array [1..maxn*maxn,1..maxn*maxn] of byte;
var d,i,j,k,m,n,mind,nextp,t:longint;
p:array [1..maxn*maxn,1..2] of longint;
g:arraytype;
r:array [1..maxn,1..maxn] of longint;
v,q:array [1..maxn*maxn] of longint;
procedure bfs(k:longint);
var i,head,tail:longint;
begin
q[1]:=k;
head:=1;
tail:=1;
v[1]:=1;
while head<=tail do
begin
inc(t);
k:=q[head];
r[p[k,1],p[k,2]]:=t;
for i:=1 to n*n do
if (g[k,i]=1) and (v[i]=0) then
begin
inc(tail);
q[tail]:=i;
v[q[tail]]:=1
end;
inc(head)
end
end;
begin
write('Input n:');
readln(n);
k:=0;
for i:=1 to n do
for j:=1 to n do
begin
inc(k);
p[k,1]:=i;
p[k,2]:=j
end;
fillchar(g,sizeof(g),0);
for i:=1 to n*n-1 do
for j:=i+1 to n*n do
if abs((p[i,1]-p[j,1])*(p[i,2]-p[j,2]))=2
then begin g[i,j]:=1; g[j,i]:=1 end;
fillchar(v,sizeof(v),0);
t:=0;
bfs(1);
for i:=1 to n do
begin
for j:=1 to n do write(r[i,j]:4);
writeln
end;
end.
type arraytype=array [1..maxn*maxn,1..maxn*maxn] of byte;
var d,i,j,k,m,n,mind,nextp,t:longint;
p:array [1..maxn*maxn,1..2] of longint;
g:arraytype;
r:array [1..maxn,1..maxn] of longint;
v,q:array [1..maxn*maxn] of longint;
procedure bfs(k:longint);
var i,head,tail:longint;
begin
q[1]:=k;
head:=1;
tail:=1;
v[1]:=1;
while head<=tail do
begin
inc(t);
k:=q[head];
r[p[k,1],p[k,2]]:=t;
for i:=1 to n*n do
if (g[k,i]=1) and (v[i]=0) then
begin
inc(tail);
q[tail]:=i;
v[q[tail]]:=1
end;
inc(head)
end
end;
begin
write('Input n:');
readln(n);
k:=0;
for i:=1 to n do
for j:=1 to n do
begin
inc(k);
p[k,1]:=i;
p[k,2]:=j
end;
fillchar(g,sizeof(g),0);
for i:=1 to n*n-1 do
for j:=i+1 to n*n do
if abs((p[i,1]-p[j,1])*(p[i,2]-p[j,2]))=2
then begin g[i,j]:=1; g[j,i]:=1 end;
fillchar(v,sizeof(v),0);
t:=0;
bfs(1);
for i:=1 to n do
begin
for j:=1 to n do write(r[i,j]:4);
writeln
end;
end.