最少转弯问题
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):
![](http://images0.cnblogs.com/blog2015/797567/201508/202046464882180.png)
![](http://images0.cnblogs.com/blog2015/797567/201508/202047264882067.png)
【解题思路】
这是一只宽搜的经典题目,过程不多讲,一定要判断初始方向,不能一开始就转向,刚开始就错在这了。
【输入格式】
第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):
![](http://images0.cnblogs.com/blog2015/797567/201508/202046464882180.png)
![](http://images0.cnblogs.com/blog2015/797567/201508/202047264882067.png)
【解题思路】
这是一只宽搜的经典题目,过程不多讲,一定要判断初始方向,不能一开始就转向,刚开始就错在这了。
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.
相关文章推荐
- 明远imx6
- 第六篇 SQL Server安全执行上下文和代码签名
- Cocos2d-x 之 八方向小摇杆
- 【ZJOI2013】K 大数查询 ( 树状数组套线段树 )
- css基础精华05
- HDU 5414 CRB and String
- Centos7下Amarok播放mp3
- curl 要么 file_get_contents 获得授权页面的方法的必要性
- hive与hbase集成
- Heartbeat概念详解
- 如何隐藏导航栏下的线
- css基础精华04
- Java值传递以及引用的传递、数组的传递!!
- android 添加视频、图片、录音上传(一)
- Html标签
- Phantomjs 根据Casperjs源码拓展download方法
- 数组的异常及处理
- Java Map和Bean之前的转换
- css基础精华03
- 下岗满月记录