|
| 1 | +//https://www.acmicpc.net/problem/4179 |
| 2 | + |
| 3 | +#include <iostream> |
| 4 | +#include <vector> |
| 5 | +#include <queue> |
| 6 | +using namespace std; |
| 7 | + |
| 8 | +int R, C; |
| 9 | +char arr[1001][1001]; |
| 10 | +bool fvisited[1001][1001]; |
| 11 | +bool jvisited[1001][1001]; |
| 12 | + |
| 13 | +const int dx[4] = {-1, 0, 1, 0}; |
| 14 | +const int dy[4] = {0, 1, 0, -1}; |
| 15 | + |
| 16 | +struct Node { |
| 17 | + int x, y; |
| 18 | +}; |
| 19 | + |
| 20 | +bool OOB(int x, int y) { |
| 21 | + return x < 0 || x >= R || y < 0 || y >= C; |
| 22 | +} |
| 23 | + |
| 24 | +Node now; |
| 25 | +queue<Node> fq; |
| 26 | +queue<Node> jq; |
| 27 | + |
| 28 | +void fbfs() { |
| 29 | + int cnt = fq.size(); |
| 30 | + while(cnt--) { |
| 31 | + Node now = fq.front(); |
| 32 | + fq.pop(); |
| 33 | + |
| 34 | + for(int dir = 0; dir < 4; dir++) { |
| 35 | + int nx = now.x + dx[dir]; |
| 36 | + int ny = now.y + dy[dir]; |
| 37 | + |
| 38 | + if (OOB(nx, ny) || fvisited[nx][ny] || arr[nx][ny] == '#') continue; |
| 39 | + fvisited[nx][ny] = true; |
| 40 | + arr[nx][ny] = 'F'; |
| 41 | + fq.push({nx, ny}); |
| 42 | + } |
| 43 | + } |
| 44 | +} |
| 45 | + |
| 46 | +int jbfs() { |
| 47 | + int time = 0; |
| 48 | + while(!jq.empty()) { |
| 49 | + time++; |
| 50 | + fbfs(); // 불 이동 |
| 51 | + |
| 52 | + int cnt = jq.size(); |
| 53 | + while(cnt--) { |
| 54 | + Node now = jq.front(); |
| 55 | + jq.pop(); |
| 56 | + |
| 57 | + for(int dir = 0; dir < 4; dir++) { |
| 58 | + int nx = now.x + dx[dir]; |
| 59 | + int ny = now.y + dy[dir]; |
| 60 | + |
| 61 | + if(OOB(nx, ny)) return time; |
| 62 | + if(jvisited[nx][ny] || arr[nx][ny] == '#' || arr[nx][ny] == 'F') continue; |
| 63 | + jvisited[nx][ny] = true; |
| 64 | + arr[nx][ny] = 'J'; |
| 65 | + jq.push({nx, ny}); |
| 66 | + } |
| 67 | + } |
| 68 | + } |
| 69 | + return -1; |
| 70 | +} |
| 71 | + |
| 72 | +int main() { |
| 73 | + ios::sync_with_stdio(false); |
| 74 | + cin.tie(0); cout.tie(0); |
| 75 | + |
| 76 | + cin >> R >> C; |
| 77 | + for(int i = 0; i < R; i++){ |
| 78 | + for(int j = 0; j < C; j++){ |
| 79 | + cin >> arr[i][j]; |
| 80 | + if (arr[i][j] == 'J') { |
| 81 | + jq.push({i, j}); |
| 82 | + } else if (arr[i][j] == 'F') { |
| 83 | + fq.push({i, j}); |
| 84 | + } |
| 85 | + } |
| 86 | + } |
| 87 | + |
| 88 | + int time = jbfs(); |
| 89 | + if (time == -1) cout << "IMPOSSIBLE"; |
| 90 | + else cout << time; |
| 91 | + |
| 92 | + return 0; |
| 93 | +} |
0 commit comments