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
| #include <bits/stdc++.h> #define int long long using namespace std;
const int N = 333; char g[N][N]; bool st[N][N]; int n, m;
struct Point{ int x, y, d; };
Point transmit(int x, int y, int d) { for (int i = 1; i <= n; i++) { for (int j = 1; j <= m; j++) { if (g[i][j] == g[x][y] && (i != x || j != y)) { return {i, j, d}; } } } }
int dx[4] = {1, 0, -1, 0}; int dy[4] = {0, 1, 0, -1};
void bfs(int x, int y) { queue<Point> q; q.push({x, y, 0}); while (!q.empty()) { auto f = q.front(); q.pop(); if (g[f.x][f.y] == '=') { cout << f.d << endl; return; } if (isalpha(g[f.x][f.y])) { f = transmit(f.x, f.y, f.d); } for (int i = 0; i < 4; i++) { x = dx[i] + f.x; y = dy[i] + f.y; if (x >= 1 && x <= n && y >= 1 && y <= m && g[x][y] != '#' && !st[x][y]) { st[x][y] = true; q.push({x, y, f.d + 1}); } } } }
void solve() { cin >> n >> m; int x, y; for (int i = 1; i <= n; i++) { for (int j = 1; j <= m; j++) { cin >> g[i][j]; if (g[i][j] == '@') { x = i; y = j; } } } bfs(x, y); }
signed main() { ios::sync_with_stdio(0);cin.tie(0);cout.tie(0); int t = 1;
while (t--) { solve(); } return 0; }
|