반응형
https://www.acmicpc.net/problem/5427
5427번: 불
상근이는 빈 공간과 벽으로 이루어진 건물에 갇혀있다. 건물의 일부에는 불이 났고, 상근이는 출구를 향해 뛰고 있다. 매 초마다, 불은 동서남북 방향으로 인접한 빈 공간으로 퍼져나간다. 벽에
www.acmicpc.net
[ 문제풀이 ]
1. queue에 불의 좌표를 먼저 넣습니다.
2. 상근이의 좌표를 queue에 넣습니다.
3. bfs를 돌면서 불을 먼저 이동시키고 이후 상근이를 이동시키면서 상근이가 범위 밖으로 벗어나면 현재까지 이동한 거리를 출력합니다.
4. queue가 빌 때까지 지훈이가 탈출하지 못하면 IMPOSSIBLE을 출력합니다.
[ 소스코드 ]
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<iostream> #include<queue> #include<cstring> using namespace std; char arr[1001][1001]; int dy[4] = { -1,1,0,0 }; int dx[4] = { 0,0,-1,1 }; int visited[1000][1000]; int w, h; struct node { int y; int x; int cur; int cnt; }; void bfs(queue<node> q) { while (!q.empty()) { const int y = q.front().y; const int x = q.front().x; const int cur = q.front().cur; const int cnt = q.front().cnt; q.pop(); for (int i = 0; i < 4; i++) { const int yy = y + dy[i]; const int xx = x + dx[i]; if (yy >= 0 && yy < h && xx >= 0 && xx < w) { if (cur == 1) { if (arr[yy][xx] == '.' || arr[yy][xx] == '@') { arr[yy][xx] = '*'; q.push({ yy,xx,cur,cnt }); } } else { if (visited[yy][xx] != 1 && arr[yy][xx] == '.') { visited[yy][xx] = 1; q.push({ yy,xx,cur,cnt + 1 }); } } } else { if (cur == 0) { printf("%d\n", cnt + 1); return; } } } } printf("IMPOSSIBLE\n"); } int main() { int T; scanf("%d", &T); for (int t = 0; t < T; t++) { memset(visited, 0, sizeof(visited)); int y, x; scanf("%d %d", &w, &h); queue<node> q; for (int i = 0; i < h; i++) { scanf("%s", arr[i]); } for (int i = 0; i < h; i++) { for (int j = 0; j < w; j++) { if (arr[i][j] == '*') { q.push({ i,j,1,0 }); } if (arr[i][j] == '@') { y = i; x = j; } } } q.push({ y,x,0,0 }); visited[y][x] = 1; bfs(q); } } | cs |
반응형
'백준' 카테고리의 다른 글
[ 백준 ] 1016번 - 제곱 ㄴㄴ 수 (C++) (0) | 2022.12.07 |
---|---|
[ 백준 ] 6091번 - 핑크 플로이드 (C++) (0) | 2022.12.06 |
[ 백준 ] 4179번 - 불! (C++) (0) | 2022.12.04 |
[ 백준 ] 10159번 - 저울 (C++) (0) | 2022.12.03 |
[ 백준 ] 14466번 - 소가 길을 건너간 이유 6 (C++) (0) | 2022.12.02 |