最小转弯问题

给一个地图,其中有障碍物,开始人在起点的面对方向任意,求从起点到终点最少转几次弯。

f[pos,x,y]表示人在(x,y)位置,面向方向pos时的最小步数,用BFS或SPFA即可。

View Code
  1 program lphone(input,output);
2 type
3 node = record
4 xx,yy,pos : integer;
5 end;
6 var
7 d : array[1..4,0..101,0..101] of longint;
8 v : array[1..4,0..101,0..101] of boolean;
9 q : array[0..400000] of node;
10 a : array[0..101,0..101] of char;
11 x : array[1..4] of longint=(-1,0,1,0);
12 y : array[1..4] of longint=(0,1,0,-1);
13 start,goal : node;
14 n,m : longint;
15 procedure init;
16 var
17 i,j : longint;
18 begin
19 readln(m,n);
20 for i:=1 to n do
21 begin
22 for j:=1 to m do
23 begin
24 read(a[i,j]);
25 if a[i,j]='C' then
26 if goal.xx=0 then
27 begin
28 goal.xx:=i;
29 goal.yy:=j;
30 end
31 else
32 begin
33 start.xx:=i;
34 start.yy:=j;
35 end;
36 end;
37 readln;
38 end;
39 end; { init }
40 procedure spfa;
41 var
42 head,tail : longint;
43 i : longint;
44 newx,newy,newpos : longint;
45 begin
46 fillchar(d,sizeof(d),63);
47 fillchar(v,sizeof(v),false);
48 head:=0;
49 tail:=4;
50 for i:=1 to 4 do
51 begin
52 q[i].xx:=start.xx;
53 q[i].yy:=start.yy;
54 q[i].pos:=i;
55 v[q[i].pos,q[i].xx,q[i].yy]:=true;
56 d[q[i].pos,q[i].xx,q[i].yy]:=0;
57 end;
58 while head<tail do
59 begin
60 inc(head);
61 v[q[head].pos,q[head].xx,q[head].yy]:=false;
62 newx:=q[head].xx+x[q[head].pos];
63 newy:=q[head].yy+y[q[head].pos];
64 if (newx>0)and(newx<=n)and(newy>0)and(newy<=m) then
65 if a[newx,newy]<>'*' then
66 if d[q[head].pos,q[head].xx,q[head].yy]<d[q[head].pos,newx,newy] then
67 begin
68 d[q[head].pos,newx,newy]:=d[q[head].pos,q[head].xx,q[head].yy];
69 if not v[q[head].pos,newx,newy] then
70 begin
71 inc(tail);
72 q[tail].xx:=newx;
73 q[tail].yy:=newy;
74 q[tail].pos:=q[head].pos;
75 v[q[head].pos,newx,newy]:=true;
76 end;
77 end;
78 newpos:=q[head].pos+1;
79 if newpos=5 then
80 newpos:=1;
81 if d[q[head].pos,q[head].xx,q[head].yy]+1<d[newpos,q[head].xx,q[head].yy] then
82 begin
83 d[newpos,q[head].xx,q[head].yy]:=d[q[head].pos,q[head].xx,q[head].yy]+1;
84 if not v[newpos,q[head].xx,q[head].yy] then
85 begin
86 inc(tail);
87 q[tail].pos:=newpos;
88 q[tail].xx:=q[head].xx;
89 q[tail].yy:=q[head].yy;
90 v[newpos,q[head].xx,q[head].yy]:=true;
91 end;
92 end;
93 newpos:=q[head].pos-1;
94 if newpos=0 then
95 newpos:=4;
96 if d[q[head].pos,q[head].xx,q[head].yy]+1<d[newpos,q[head].xx,q[head].yy] then
97 begin
98 d[newpos,q[head].xx,q[head].yy]:=d[q[head].pos,q[head].xx,q[head].yy]+1;
99 if not v[newpos,q[head].xx,q[head].yy] then
100 begin
101 inc(tail);
102 q[tail].pos:=newpos;
103 q[tail].xx:=q[head].xx;
104 q[tail].yy:=q[head].yy;
105 v[newpos,q[head].xx,q[head].yy]:=true;
106 end;
107 end;
108 end;
109 end; { spfa }
110 procedure print;
111 var
112 i,min : longint;
113 begin
114 min:=maxlongint>>1;
115 for i:=1 to 4 do
116 if d[i,goal.xx,goal.yy]<min then
117 min:=d[i,goal.xx,goal.yy];
118 writeln(min);
119 end; { print }
120 begin
121 init;
122 spfa;
123 print;
124 end.



posted @ 2012-03-18 15:08  Codinginging  阅读(568)  评论(0编辑  收藏  举报