|
| 1 | +//https://www.acmicpc.net/problem/2206 |
| 2 | +#include <iostream> |
| 3 | +#include <vector> |
| 4 | +#include <algorithm> |
| 5 | +#include <queue> |
| 6 | + |
| 7 | +using namespace std; |
| 8 | + |
| 9 | +struct Node { |
| 10 | + int x, y; |
| 11 | +}; |
| 12 | + |
| 13 | +int N, M; |
| 14 | +char arr[1001][1001]; |
| 15 | +bool visited[1001][1001][2]; // 벽 부수기 상태 |
| 16 | +const int dx[4] = {-1, 0, 1, 0}; |
| 17 | +const int dy[4] = {0, 1, 0, -1}; |
| 18 | + |
| 19 | +bool OOB(int x, int y) { |
| 20 | + return x < 0 || x >= N || y < 0 || y >= M; |
| 21 | +} |
| 22 | + |
| 23 | +int bfs(int x, int y) { |
| 24 | + queue<pair<Node, pair<int, int>>> q; // state, dist |
| 25 | + q.push({{x, y}, {false, 1}}); |
| 26 | + visited[x][y][0] = true; |
| 27 | + |
| 28 | + while(!q.empty()) { |
| 29 | + pair<Node, pair<int, int>> now = q.front(); |
| 30 | + bool used = now.second.first; |
| 31 | + int dist = now.second.second; |
| 32 | + q.pop(); |
| 33 | + |
| 34 | + if (now.first.x == N - 1 && now.first.y == M - 1) { |
| 35 | + return dist; |
| 36 | + } |
| 37 | + |
| 38 | + for(int dir = 0; dir < 4; dir++){ |
| 39 | + int nx = now.first.x + dx[dir]; |
| 40 | + int ny = now.first.y + dy[dir]; |
| 41 | + |
| 42 | + if (OOB(nx, ny)) continue; |
| 43 | + |
| 44 | + // 벽 O |
| 45 | + // 벽 부신 적 없을 때만 가능 |
| 46 | + if (arr[nx][ny] == '1') { |
| 47 | + if (!used && !visited[nx][ny][!used]) { |
| 48 | + visited[nx][ny][!used] = true; |
| 49 | + q.push({{nx, ny}, {!used, dist + 1}}); |
| 50 | + } |
| 51 | + } |
| 52 | + // 벽 X |
| 53 | + // 그냥 이동 |
| 54 | + else { |
| 55 | + if (!visited[nx][ny][used]) { |
| 56 | + visited[nx][ny][used] = true; |
| 57 | + q.push({{nx, ny}, {used, dist + 1}}); |
| 58 | + } |
| 59 | + } |
| 60 | + } |
| 61 | + } |
| 62 | + return -1; |
| 63 | +} |
| 64 | + |
| 65 | +int main(){ |
| 66 | + ios_base::sync_with_stdio(false); |
| 67 | + cin.tie(NULL); cout.tie(NULL); |
| 68 | + |
| 69 | + cin >> N >> M; |
| 70 | + for(int i = 0; i < N; i++){ |
| 71 | + for(int j = 0; j < M; j++){ |
| 72 | + cin >> arr[i][j]; |
| 73 | + } |
| 74 | + } |
| 75 | + cout << bfs(0, 0); |
| 76 | + |
| 77 | + return 0; |
| 78 | +} |
0 commit comments