1 #include<stdio.h>
2 #include<string.h>
3 #include<math.h>
4 #include<iostream>
5 #include<algorithm>
6 #include<queue>
7 #include<vector>
8 #include<set>
9 #include<stack>
10 #include<string>
11 #include<sstream>
12 #include<map>
13 #include<cctype>
14 using namespace std;
15 int n,m,b[4][2]={0,-1,0,1,-1,0,1,0},minn,visited[105][105],vis[105][105];
16 char a[105][105];
17 struct monkey
18 {
19 int x,y,step;
20 };
21 queue<monkey>Q;
22 void pretreatment(int x,int y,char b,char c) //坐标 和 该名称 和 另一人名称
23 {
24 for(int i=x+1;i<m&&a[y][i]!='X'&&a[y][i]!=c;i++)
25 a[y][i]=(a[y][i]=='d'?'O':b+32);
26 for(int i=x-1;i>=0&&a[y][i]!='X'&&a[y][i]!=c;i--)
27 a[y][i]=(a[y][i]=='d'?'O':b+32);
28 for(int i=y+1;i<n&&a[i][x]!='X'&&a[i][x]!=c;i++)
29 a[i][x]=(a[i][x]=='d'?'O':b+32);
30 for(int i=y-1;i>=0&&a[i][x]!='X'&&a[i][x]!=c;i--)
31 a[i][x]=(a[i][x]=='d'?'O':b+32);
32 }
33 queue<monkey>W;
34 void BFSMORE(int x,int y,int step,char c)
35 {
36 monkey q={x,y,step};
37 W.push(q);
38 while(!W.empty())
39 {
40 monkey e=W.front();
41 W.pop();
42 for(int i=0;i<4;i++)
43 {
44 q.x=e.x+b[i][0],q.y=e.y+b[i][1];
45 if(a[q.y][q.x]!='X'&&a[q.y][q.x]!='D'&&a[q.y][q.x]!='E'&&q.x>=0&&q.x<m&&q.y>=0&&q.y<n&&!vis[q.y][q.x])
46 {
47 vis[q.y][q.x]=1;
48 q.step=e.step+1;
49 W.push(q);
50 if(a[q.y][q.x]==c||a[q.y][q.x]=='O')
51 {
52 minn=minn>q.step?q.step:minn;
53 while(!W.empty())
54 W.pop();
55 break;
56 }
57 }
58 }
59 }
60 }
61 void BFS(int x,int y)
62 {
63 monkey q={x,y,0};
64 if(a[y][x]=='O')
65 {
66 minn=0;
67 return ;
68 }
69 if(a[y][x]=='d')
70 {
71 memset(vis,0,sizeof(vis));
72 BFSMORE(x,y,0,'e');
73 }
74 if(a[y][x]=='e')
75 {
76 memset(vis,0,sizeof(vis));
77 BFSMORE(x,y,0,'d');
78 }
79 Q.push(q);
80 while(!Q.empty())
81 {
82 monkey e=Q.front();
83 Q.pop();
84 for(int i=0;i<4;i++)
85 {
86 q.x=e.x+b[i][0],q.y=e.y+b[i][1];
87 if(a[q.y][q.x]!='X'&&a[q.y][q.x]!='D'&&a[q.y][q.x]!='E'&&q.x>=0&&q.x<m&&q.y>=0&&q.y<n&&!visited[q.y][q.x])
88 {
89 q.step=e.step+1;
90 Q.push(q);
91 visited[q.y][q.x]=1;
92 if(a[q.y][q.x]=='O')
93 {
94 minn=minn>q.step?q.step:minn;
95 }
96 if(a[q.y][q.x]=='d')
97 {
98 memset(vis,0,sizeof(vis));
99 BFSMORE(q.x,q.y,q.step,'e');
100 }
101 if(a[q.y][q.x]=='e')
102 {
103 memset(vis,0,sizeof(vis));
104 BFSMORE(q.x,q.y,q.step,'d');
105 }
106 }
107 }
108 }
109 }
110 int main()
111 {
112 int sx,sy,dx,dy,ex,ey,t,count1=0;
113 while(scanf("%d%d%d",&n,&m,&t)!=EOF)
114 {
115 minn=t+1;
116 for(int i=0;i<n;i++)
117 {
118 for(int j=0;j<m;j++)
119 {
120 scanf(" %c",&a[i][j]);
121 if(a[i][j]=='S')
122 {
123 sx=j;
124 sy=i;
125 }
126 if(a[i][j]=='D')
127 {
128 dx=j;
129 dy=i;
130 }
131 if(a[i][j]=='E')
132 {
133 ex=j;
134 ey=i;
135 }
136 }
137 }
138 pretreatment(dx,dy,'D','E');
139 pretreatment(ex,ey,'E','D');
140 memset(visited,0,sizeof(visited));
141 visited[sy][sx]=1;
142 BFS(sx,sy);
143 printf("Case %d:
",++count1);
144 if(minn<=t)
145 printf("%d
",minn);
146 else
147 printf("-1
");
148 }
149 return 0;
150 }