您的位置:首页 > 其它

最少转弯问题

2015-08-20 20:52 375 查看
给出一张地图,这张地图被分为n×m(n,m<=100)个方块,任何一个方块不是平地就是高山。平地可以通过,高山则不能。现在你处在地图的(x1,y1)这块平地,问:你至少需要拐几个弯才能到达目的地(x2,y2)?你只能沿着水平和垂直方向的平地上行进,拐弯次数就等于行进方向的改变(从水平到垂直或从垂直到水平)的次数。例如:如图1,最少的拐弯次数为5。

【输入格式】

第1 行:n m

第2 至n+1行:整个地图地形描述(0:空地;1:高山),

如(图1)第2 行地形描述为:1 0 0 0 0 1 0

第3 行地形描述为:0 0 1 0 1 0 0

……

第n+2 行:x1 y1 x2 y2 (分别为起点、终点坐标)

【输出格式】

s (即最少的拐弯次数)

【输入输出样例】(见图1):





【解题思路】

这是一只宽搜的经典题目,过程不多讲,一定要判断初始方向,不能一开始就转向,刚开始就错在这了。

program t4;
const fx:array[1..4] of longint=(0,1,0,-1);
fy:array[1..4] of longint=(-1,0,1,0);
var dt:array[1..100000,1..2] of longint;
d,ans:array[1..100000] of longint;
f:array[1..100,1..100] of longint;
pd:array[1..100,1..100] of longint;
x1,x2,y1,y2,i,j,h,t,sum,n,m:Longint;
begin
filldword(pd,sizeof(pd) div 4,maxlongint div 2);
read(n,m);
for i:=1 to n do
for j:=1 to m do read(f[i,j]);
read(x1,y1,x2,y2);
for i:=1 to 4 do
begin
if (x1+fx[i]>0) and(x1+fx[i]<=n) and(y1+fy[i]>0) and (y1+fy[i]<=n)
and(f[x1+fx[i],y1+fy[i]]=0) then//重点在这
begin
inc(t);
dt[t,1]:=x1;
dt[t,2]:=y1;
d[t]:=i;
end;
end;
while h<=t do
begin
inc(h);
sum:=1;
while (dt[h,1]+fx[d[h]]*sum>0) and (dt[h,2]+fy[d[h]]*sum>0)
and (dt[h,1]+fx[d[h]]*sum<=n) and (dt[h,2]+fy[d[h]]*sum<=m)
and (f[dt[h,1]+fx[d[h]]*sum,dt[h,2]+fy[d[h]]*sum]<>1)
//and (not pd[dt[h,1]+fx[d[h]]*sum,dt[h,2]+fy[d[h]]*sum])
do
begin
inc(t);
dt[t,1]:=dt[h,1]+fx[d[h]]*sum;
dt[t,2]:=dt[h,2]+fy[d[h]]*sum;
d[t]:=d[h];
ans[t]:=ans[h];
',dt[h,2]+fy[d[h]]*sum,' ',ans[t]);
if (dt[h,1]+fx[d[h]]*sum=x2)and(dt[h,2]+fy[d[h]]*sum=y2) then
begin
writeln(ans[h]);
halt;
end;
inc(sum);
end;
for i:=1 to 4 do
if i mod 2<>d[h] mod 2 then
begin
if (dt[h,1]+fx[i]>0) and (dt[h,2]+fy[i]>0) and
(dt[h,1]+fx[i]<=n) and (dt[h,2]+fy[i]<=m) and
(f[dt[h,1]+fx[i],dt[h,2]+fy[i]]<>1)
then
begin
inc(t);
dt[t,1]:=dt[h,1]+fx[i];
dt[t,2]:=dt[h,2]+fy[i];
d[t]:=i;
ans[t]:=ans[h]+1;
//writeln(dt[h,1]+fx[i],' ',dt[h,2]+fy[i],' ',ans[t]);
if (dt[h,1]+fx[i]=x2)and(dt[h,2]+fy[i] =y2) then
begin
writeln(ans[t]);
halt;
end;
end;
end;

end;
end.
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: