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 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119
|
#include <cstdio> #include <queue> #include <iostream> #include <algorithm> #include <cstring>
using namespace std;
char mp[5005][5005]; int dist1[5005][5005], dist2[5005][5005]; constexpr int dx1[] = {0, 0, 1, -1}; constexpr int dy1[] = {1, -1, 0, 0}; constexpr int dx2[] = {1, 1, -1, -1}; constexpr int dy2[] = {1, -1, 1, -1}; int main() { memset(dist1, 0x3f, sizeof dist1); memset(dist2, 0x3f, sizeof dist2); int n, m; scanf("%d%d", &n, &m); int xx, xy, wx, wy; for(int i=1;i<=n;i++) { while(getchar() != '\n'); for(int j=1;j<=m;j++) { mp[i][j] = getchar(); if(mp[i][j] == 'X') { xx = i; xy = j; mp[i][j] = '.'; } if(mp[i][j] == 'W') { wx = i; wy = j; mp[i][j] = '.'; } } } int sx = xx, sy = xy; deque<pair<int, int>> q1; dist1[sx][sy] = 0; dist2[sx][sy] = 0; q1.push_back({sx, sy}); while(!q1.empty()) { pair<int, int> u = q1.front(); q1.pop_front(); int x = u.first, y = u.second; for(int i=0;i<4;i++) { int ux = x + dx2[i], uy = y + dy2[i]; if(mp[ux][uy] == '.' && dist1[x][y] < dist1[ux][uy]) { dist1[ux][uy] = dist1[x][y]; q1.push_front({ux, uy}); } } for(int i=0;i<4;i++) { int ux = x + dx1[i], uy = y + dy1[i]; if(mp[ux][uy] == '.' && dist1[x][y] + 1 < dist1[ux][uy]) { dist1[ux][uy] = dist1[x][y] + 1; q1.push_back({ux, uy}); } } }
if(dist1[wx][wy] == 0x3f3f3f3f) { printf("-1 -1\n"); return 0; } deque<pair<int, int>> q2; q2.push_back({sx, sy}); while(!q2.empty()) { pair<int, int> u = q2.front(); q2.pop_front(); int x = u.first, y = u.second; for(int i=0;i<4;i++) { int vx = x + dx1[i], vy = y + dy1[i]; if(mp[vx][vy] == '.' && dist1[x][y] + 1 == dist1[vx][vy] && dist2[x][y] < dist2[vx][vy]) { dist2[vx][vy] = dist2[x][y]; q2.push_front({vx, vy}); } } for(int i=0;i<4;i++) { int vx = x + dx2[i], vy = y + dy2[i]; if(mp[vx][vy] == '.' && dist1[x][y] == dist1[vx][vy] && dist2[x][y] + 1 < dist2[vx][vy]) { dist2[vx][vy] = dist2[x][y] + 1; q2.push_back({vx, vy}); } } } printf("%d %d\n", dist1[wx][wy], dist2[wx][wy]); return 0; }
|