1002 - 解救小Q

1002 - 解救小Q

简单搜索题,求最短路径,优先使用 BFS ,唯一需要注意的地方就是传送阵,传送阵联通的两点的深度一致为了避免在搜索中寻找传送阵,我们可以在输入过程中,对传送阵两点进行关联。搜索过程中,若遇见传送阵,我们只需把与这一传送阵的另一端入队即可,而当前搜索遇到的这一端无需入队。

下面附上AC代码以及注释,希望能帮助到大家:

View Code
1 #include<iostream>
2 using namespace std;
3 int vis[51][51],ans,n,m,dx[4]={-1,0,1,0},dy[5]={0,1,0,-1};
4 struct trans
5 { int y,x;
6 }a[2][30];
7 struct node
8 { int c,d,step;
9 }b[10000];
10 bool flag;char map[51][51];
11 int main()
12 { int T;
13 cin>>T;
14 while(T--)
15 { cin>>n>>m;
16 flag=false;
17 int head=0,tail=1,vis1[30]={0};
18 ans=101;
19 for(int i=1;i<=n;i++)
20 {
21 for(int j=1;j<=m;j++)
22 { cin>>map[i][j];vis[i][j]=0;
23 if(map[i][j]=='L') map[i][j]='#',b[0].c=i,b[0].d=j;
24 else if(map[i][j]>='a' && map[i][j]<='z')
25 { int k=map[i][j]-'a';
26 if(vis1[k]==0) a[0][k].y=i,a[0][k].x=j,vis1[k]=1;
27 else a[1][k].y=i,a[1][k].x=j;
28 }
29 }
30 }
31 b[0].step=0;
32 while(head<tail)
33 { for(int i=0;i<4;i++)
34 { int tx=b[head].d+dx[i],ty=b[head].c+dy[i],k1,k2;
35 if(tx>0&&tx<=m&&ty>0&&ty<=n&&map[ty][tx]!='#'&&vis[ty][tx]==0)
36 { vis[ty][tx]=1;
37 if(map[ty][tx]>='a' && map[ty][tx]<='z')
38 {
39 int k=map[ty][tx]-'a';
40 if(a[0][k].y==ty && a[0][k].x==tx) k1=a[1][k].y,k2=a[1][k].x;
41 else k1=a[0][k].y,k2=a[0][k].x;
42 b[tail].c=k1,b[tail].d=k2;
43 b[tail].step=b[head].step+1;tail+=1;
44 }
45 else
46 { b[tail].c=ty,b[tail].d=tx;
47 b[tail].step=b[head].step+1;
48 if(map[ty][tx]=='Q') {flag=true;cout<<b[tail].step<<endl;} tail+=1;
49 }
50 }
51 }
52 head+=1;
53 }
54 if(flag==false) cout<<"-1"<<endl;
55 }
56 }
57
posted @ 2011-04-16 21:06  nightstaker  阅读(489)  评论(2)    收藏  举报