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 80 81 82 83 84 85 86 87 88 89 90 91
| #include<bits/stdc++.h> #define LL long long
using namespace std;
const int MAXN = 1005; const int MAXD = MAXN * MAXN;
const int dx1[] = {2, -2, 0, 0}; const int dy1[] = {0, 0, 2, -2}; const int dx2[] = {1, -1, 0, 0}; const int dy2[] = {0, 0, 1, -1};
LL n, m; string g[MAXN];
int edgeCount; int head[MAXD], toNode[MAXD << 4], nextEdge[MAXD << 4]; int edgeWeight[MAXD << 4];
priority_queue<pair<int, int>, vector<pair<int, int>>, greater<pair<int, int>>> pq; int dis[MAXD]; bool vis[MAXD];
inline int ind(int x, int y) { return (x - 1) * m + y; } inline void addEdge(int from, int to, int weight) { edgeCount++; toNode[edgeCount] = to; nextEdge[edgeCount] = head[from]; edgeWeight[edgeCount] = weight; head[from] = edgeCount; return; }
int main() { ios::sync_with_stdio(false); cin.tie(nullptr); cout.tie(nullptr); cin >> n >> m; for (int i = 1; i <= n; ++i) cin >> g[i]; for (int i = 1; i <= n; ++i) for (int j = 1; j <= m; ++j) { if (g[i][j - 1] == '.') for (int k = 0; k < 4; ++k) { int xx = i + dx2[k]; int yy = j + dy2[k]; if (1 <= xx && xx <= n && 1 <= yy && yy <= m && g[xx][yy - 1] == '.') { addEdge(ind(i, j), ind(xx, yy), 0); addEdge(ind(xx, yy), ind(i, j), 0); } } for (int k = 0; k < 4; ++k) { int xx = i + dx1[k]; int yy = j + dy1[k]; if (1 <= xx && xx <= n && 1 <= yy && yy <= m) { addEdge(ind(i, j), ind(xx, yy), 1); addEdge(ind(xx, yy), ind(i, j), 1); } } } memset(dis, 0x3f, sizeof(dis)); pq.push({0, ind(1, 1)}); dis[ind(1, 1)] = 0; while (!pq.empty()) { int from = pq.top().second; pq.pop(); if (vis[from]) continue; vis[from] = true; for (int i = head[from]; i; i = nextEdge[i]) { int to = toNode[i]; int curDis = dis[from] + edgeWeight[i]; if (dis[to] > curDis) { dis[to] = curDis; pq.push({dis[to], to}); } } } if (dis[ind(n, m)] == 0x3f3f3f3f) cout << -1, exit(0); cout << dis[ind(n, m)]; return 0; }
|