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[100000];
10 bool flag;char map[51][51];
11 void dfs(int x,int y,int step)
12 { if(map[y][x]=='Q') {flag=true;ans=ans>step?step:ans;}
13 else
14 for(int i=0;i<4;i++)
15 { int tx=x+dx[i],ty=y+dy[i],k1,k2;
16 if(tx>0&&tx<=m&&ty>0&&ty<=n&&map[ty][tx]!='#'&&vis[ty][tx]==0)
17 { vis[ty][tx]=1;
18 if(map[ty][tx]>='a' && map[ty][tx]<='z')
19 { int k=map[ty][tx]-'a';
20 if(a[0][k].y==ty && a[0][k].x==tx) k1=a[1][k].y,k2=a[1][k].x;
21 else k1=a[0][k].y,k2=a[0][k].x;
22 vis[k1][k2]=1;
23 dfs(k2,k1,step+1);
24
25 vis[k1][k2]=0;
26 }
27 else
28 dfs(tx,ty,step+1);
29 vis[ty][tx]=0;
30 }
31 }
32 }
33 int main()
34 { int T;
35 cin>>T;
36 while(T--)
37 { cin>>n>>m;
38 flag=false;
39 int head=0,tail=1,vis1[30]={0};
40 ans=101;
41 for(int i=1;i<=n;i++)
42 {
43 for(int j=1;j<=m;j++)
44 { cin>>map[i][j];vis[i][j]=0;
45 if(map[i][j]=='L') map[i][j]='#',b[0].c=i,b[0].d=j;
46 else if(map[i][j]>='a' && map[i][j]<='z')
47 { int k=map[i][j]-'a'; if(vis1[k]==0) a[0][k].y=i,a[0][k].x=j,vis1[k]=1;
48 else a[1][k].y=i,a[1][k].x=j;
49 }
50 }
51 }
52 b[0].step=0;
53 while(head<tail)
54 { for(int i=0;i<4;i++)
55 { int tx=b[head].d+dx[i],ty=b[head].c+dy[i],k1,k2;
56 if(tx>0&&tx<=m&&ty>0&&ty<=n&&map[ty][tx]!='#'&&vis[ty][tx]==0)
57 { vis[ty][tx]=1;
58 if(map[ty][tx]>='a' && map[ty][tx]<='z')
59 { int k=map[ty][tx]-'a';
60 if(a[0][k].y==ty && a[0][k].x==tx) k1=a[1][k].y,k2=a[1][k].x;
61 else k1=a[0][k].y,k2=a[0][k].x;
62 b[tail].c=k1,b[tail].d=k2;
63 b[tail].step=b[head].step+1;tail+=1;
64
65 }
66 else
67 { b[tail].c=ty,b[tail].d=tx;
68 b[tail].step=b[head].step+1;
69 if(map[ty][tx]=='Q') {flag=true;cout<<b[tail].step<<endl;} tail+=1;
70 }
71 }
72 }
73 head+=1;
74 }
75 if(flag==false) cout<<"-1"<<endl;
76 }
77 }
78
posted @ 2011-04-16 21:02  nightstaker  阅读(236)  评论(0)    收藏  举报