最少转弯问题
Description
給出一張地圖,這張地圖被分為n×m(n,m<=100)個方塊,任何一個方塊不是平地就是高山。平地可以通過,高山則不能。現在你處在地圖的(x1,y1)這塊平地,問:你至少需要拐幾個彎才能到達目的地(x2,y2)?你只能沿著水平和垂直方向的平地上行進,拐彎次數就等于行進方向的改變(從水平到垂直或從垂直到水平)的次數。例如:如圖1,最少的拐彎次數為5。
Input
第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 (分別為起點、終點坐標)
Output
s (即最少的拐彎次數)
Sample Input
5 7
1 0 0 0 0 1 0
0 0 1 0 1 0 0
0 0 0 0 1 0 1
0 1 1 0 0 0 0
0 0 0 0 1 1 0
1 3 1 7
Sample Output
5
程序:
const dx:array[1..4]of longint=(1,-1,0,0); dy:array[1..4]of longint=(0,0,-1,1);var r,c,e1,e2,b1,b2:longint; a:array[0..501,0..501]of longint; f:array[0..250001]of longint; s:array[0..250001,1..3]of longint;procedure init; var ch:char; i,j:longint; beginreadln(r,c);for i:=1 to r dobeginfor j:=1 to c doread(a[i,j]); readln;end;read(b1,b2,e1,e2); end;function ping(x,y:longint):boolean; beginif (x<1)or(x>r)or(y<1)or(y>c)then exit(true);if a[x,y]=1 then exit(true);exit(false); end;procedure bfs; var h,t,i,l:longint; beginh:=0;t:=1;f[1]:=0;s[1,1]:=b1;s[1,2]:=b2;repeatinc(h);for i:=1 to 4 doif not ping(s[h,1]+dx[i],s[h,2]+dy[i]) thenbeginl:=h;while not ping(s[l,1]+dx[i],s[l,2]+dy[i]) dobegininc(t);s[t,1]:=s[l,1]+dx[i];s[t,2]:=s[l,2]+dy[i];s[t,3]:=s[h,3];a[s[t,1],s[t,2]]:=1;if (s[t,1]=e1)and(s[t,2]=e2)thenbeginwriteln(s[t,3]);exit;end;l:=t;inc(s[t,3]);end;end;until h=t; end;begininit;bfs; end.轉載于:https://www.cnblogs.com/YYC-0304/p/9500076.html
總結
- 上一篇: JZOJ__Day 10:【普及模拟】【
- 下一篇: 小游戏game