program migong;
const dx:array[1..4]of integer=(0,-1,0,1);
dy:array[1..4]of integer=(1,0,-1,0);
type pos=record
x,y:integer;
end;
var dis:array[0..1001,0..1001]of integer;
sx,sy,x,y,gx,gy,i,j:longint;
head,tail:longint;
n:longint;
ch:char;
list:array[1..1000000]of pos;
procedure BFS;
var k:integer;
begin
dis[sx,sy]:=0;
list[1].x:=sx; list[1].y:=sy;
head:=0;tail:=1;
repeat
inc(head);
for k:=1 to 4 do
begin
x:=list[head].x+dx[k];
y:=list[head].y+dy[k];
if dis[x,y]=-1 then begin
inc(tail); list[tail].x:=x;list[tail].y:=y;
dis[x,y]:=dis[list[head].x,list[head].y]+1;
if (x=gx)and(y=gy) then begin
write(dis[x,y]);exit; end;
end;
end;
until(head>tail);
write(No Answer!);
end;
{11111111111111111111111111111111111111111111111111111111111}
begin
fillchar(dis,sizeof(dis),0);
fillchar(list,sizeof(list),0);
readln(n);
for i:=1 to n do
begin
for j:=1to n do
begin
read(ch);
if ch=0 then dis[i,j]:=-1;
end;
readln;
end;
readln(sx,sy);
readln(gx,gy);
if (sx=gx)and(sy=gy)then write(0) else BFS;
end.
map:array[1..1000,1..1000] of char;
dui:array[1..1000000,1..3] of longint;
f:array[1..4,1..2] of integer=((1,0),(0,1),(-1,0),(0,-1));
i,j,k,n,m,l,top,en,x,y,step,x1,y1,total:longint;
procedure can(x,y:longint);
var
i,j,k:longint;
begin
if map[x,y]=1 then exit;
en:=en mod 1000000+1;
dui[en,1]:=x;
dui[en,2]:=y;
dui[en,3]:=step+1;
inc(total);
map[x,y]:=1;
end;
begin
readln(n);
for i:=1 to n do
begin
for j:=1 to n do read(map[i,j]);
readln;
end;
readln(x,y);
readln(x1,y1);
top:=1;
en:=1;
dui[1,1]:=x;
dui[1,2]:=y;
total:=1;
while total>0 do
begin
x:=dui[top,1];
y:=dui[top,2];
step:=dui[top,3];
top:=top mod 1000000+1;
dec(total);
if (x=x1)and(y=y1) then
begin
write(step);
halt;
end;
for i:=1 to 4 do
if (x+f[i,1]>0)and(x+f[i,1]<=n)and(y+f[i,2]>0)and(y+f[i,2]<=n) then
can(x+f[i,1],y+f[i,2]);
end;
end.
BFS,没错,可能你队列超了或者没判重!
但是如果不只入队一次的情况的话,需要用到循环队列,循环队列的大小一般是节点数*K,K是小常数
当然这是我自己的方法!