###### 1002CDOJ(解救小Q）

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

#### TOJ 2939 解救小Q / 广搜

2013-08-24 00:22:19

#### 啊哈算法BFS应用之解救小哈

2016-10-03 18:03:53

#### [Aha]解救小哈

2017-03-06 20:25:47

#### 牛客网-解救小易

2017-08-19 09:43:04

#### Uestc-1002-解救小Q

2013-05-09 20:36:14

#### 啊哈算法DFS应用之解救小哈

2016-10-03 16:58:46

#### 解救小Q（bfs）

2015-12-10 19:27:42

#### 解救小Q(BFS)

2013-12-14 22:25:32

#### CDOJ 解救小Q

2014-05-17 16:33:17

#### 解救小Q

2016-07-13 19:04:17

1002CDOJ(解救小Q）