1 #include<queue>
2 #include<cstdio>
3 #include<cstring>
4 #include<iostream>
5 #include<algorithm>
6
7 using namespace std;
8
9 struct door
10 {
11 int x,y;
12 }e[110];
13
14 int n,cnt,ce;
15 char a[15][15];
16 int b[15][15];
17 int dir[4][2] = {0,1,0,-1,1,0,-1,0};
18
19
20 struct node
21 {
22 int x,y,s,cnt;
23 };
24
25 void bfs(int x,int y)
26 {
27 memset(b,0,sizeof(b));
28 a[x][y] = ‘.‘;
29 b[x][y] = 1;
30 queue<node> q;
31 node t,next;
32 t.x = x;
33 t.y = y;
34 t.s = 0;
35 t.cnt = 1;
36 q.push(t);
37 while(!q.empty())
38 {
39 t = q.front();
40 q.pop();
41 if(t.cnt == cnt)
42 {
43 printf("%d\n",t.s);
44 return;
45 }
46 for(int i=0;i<4;i++)
47 {
48 int tx = t.x + dir[i][0];
49 int ty = t.y + dir[i][1];
50 if(tx < 0 || ty < 0 || tx >= n || ty >= n)
51 continue;
52 if(a[tx][ty] == ‘#‘ || b[tx][ty])
53 continue;
54 if(a[tx][ty] >= ‘A‘ && a[tx][ty] <= ‘Z‘ && a[tx][ty] != ‘A‘ + t.cnt)
55 continue;
56 if(a[tx][ty] >= ‘A‘ && a[tx][ty] <= ‘Z‘)
57 {
58 next.x = tx;
59 next.y = ty;
60 next.s = t.s + 1;
61 next.cnt = t.cnt + 1;
62 a[tx][ty] = ‘.‘;
63 memset(b,0,sizeof(b));
64 while(!q.empty())
65 q.pop();
66 b[tx][ty] = 1;
67 q.push(next);
68 break;
69 }
70 if(a[tx][ty] == ‘$‘)
71 {
72 for(int j=0;j<ce;j++)
73 {
74 if(e[j].x == tx && e[j].y == ty)
75 continue;
76 if(b[e[j].x][e[j].y])
77 continue;
78 next.x = e[j].x;
79 next.y = e[j].y;
80 next.s = t.s + 1;
81 next.cnt = t.cnt;
82 b[e[j].x][e[j].y] = 1;
83 q.push(next);
84 continue;
85 }
86 continue;
87 }
88 next.x = tx;
89 next.y = ty;
90 next.s = t.s + 1;
91 next.cnt = t.cnt;
92 b[tx][ty] = 1;
93 q.push(next);
94 }
95 }
96 printf("Impossible\n");
97 }
98 int main(void)
99 {
100 int T,i,j,x,y;
101 while(scanf("%d",&n)==1)
102 {
103 cnt = 0;
104 ce = 0;
105 for(i=0;i<n;i++)
106 {
107 scanf("%s",a[i]);
108 for(j=0;j<n;j++)
109 {
110 if(a[i][j] == ‘A‘)
111 x = i, y = j;
112 if(a[i][j] >= ‘A‘ && a[i][j] <= ‘Z‘)
113 cnt++;
114 if(a[i][j] == ‘$‘)
115 {
116 e[ce].x = i;
117 e[ce++].y = j;
118 }
119 }
120 }
121 bfs(x,y);
122 }
123
124 return 0;
125 }