1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
| #include <bits/stdc++.h>
using namespace std;
typedef long long ll;
const int inf = 0x3f3f3f3f;
const int N = 100 + 10;
int n, m, sx, sy, ex, ey, minn = inf;
char s[N][N];
int vis[N][N][(1 << 10) + 10];
int go[4][2] = {1, 0, -1, 0, 0, 1, 0, -1};
struct node
{
int x, y, step, key;
node() {}
node(int _x, int _y, int _step, int _key)
{
x = _x, y = _y, step = _step, key = _key;
}
};
int pd(int x, int y)
{
if (x >= 1 && x <= n && y >= 1 && y <= m)
return 1;
return 0;
}
int bfs()
{
node now(sx, sy, 0, 0), to;
vis[sx][sy][0] = 1;
queue<node> q;
q.push(now);
while (!q.empty())
{
now = q.front();
q.pop();
if (now.x == ex && now.y == ey)
return now.step;
for (int i = 0; i < 4; i++)
{
to.x = now.x + go[i][0];
to.y = now.y + go[i][1];
to.step = now.step + 1;
to.key = now.key;
if (pd(to.x, to.y) && s[to.x][to.y] != '0' && !vis[to.x][to.y][to.key])
{
if (s[to.x][to.y] >= 'A' && s[to.x][to.y] <= 'Z')
{
int key = to.key | (1 << (s[to.x][to.y] - 'A'));
if (key != to.key)
continue;
}
if (s[to.x][to.y] >= 'a' && s[to.x][to.y] <= 'z')
{
to.key |= (1 << (s[to.x][to.y] - 'a'));
}
vis[to.x][to.y][to.key] = 1;
q.push(to);
}
}
}
return 0;
}
int main()
{
//freopen("in.txt", "r", stdin);
scanf("%d%d", &n, &m);
for (int i = 1; i <= n; i++)
{
scanf("%s", s[i] + 1);
for (int j = 1; j <= m; j++)
{
if (s[i][j] == '2')
sx = i, sy = j;
if (s[i][j] == '3')
ex = i, ey = j;
}
}
printf("%d\n", bfs());
return 0;
}
|