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
| #include <cstring> #include <deque> #include <iostream> using namespace std; const int N = 1010, INF = 0x3f3f3f3f; int n, m; char grid[N][N]; int dist[N][N][4]; int dx[] = {1, -1, 0, 0}; int dy[] = {0, 0, 1, -1}; struct Status { int x, y, dir; Status(const int _x, const int _y, const int _dir) : x(_x), y(_y), dir(_dir){}; }; deque<Status> q; void Front(const Status u, int d) { if (dist[u.x][u.y][u.dir] <= d) return; dist[u.x][u.y][u.dir] = d; q.push_front(Status(u.x, u.y, u.dir)); } void Back(const Status u, int d) { if (dist[u.x][u.y][u.dir] <= d) return; dist[u.x][u.y][u.dir] = d; q.push_back(Status(u.x, u.y, u.dir)); } int main() { cin >> n >> m; for (int i = 1; i <= n; i++) for (int j = 1; j <= m; j++) cin >> grid[i][j]; memset(dist, 0x3f, sizeof(dist)); Front(Status(n, m, 3), 0); while (!q.empty()) { Status u = q.front(); q.pop_front(); int now = dist[u.x][u.y][u.dir]; int nx = u.x + dx[u.dir], ny = u.y + dy[u.dir]; if (1 <= nx && nx <= n && 1 <= ny && ny <= m) Front(Status(nx, ny, u.dir), now); if (grid[u.x][u.y] == '#') for (int i = 0; i < 4; i++) if (i != u.dir) Back(Status(u.x, u.y, i), now + 1); } if (dist[1][1][3] == INF) cout << -1; else cout << dist[1][1][3]; return 0; }
|