반응형
문제 출처 :
https://www.acmicpc.net/problem/3055
알고리즘 분석 :
문제 해결에 필요한 사항
1. BFS
이 문제는 BFS 2번으로 문제를 해결할 수 있다.
비슷한 문제는 다음 문제를 참고해보자.
http://www.crocus.co.kr/search/%EB%B6%88 에서 불, FIRE 문제를 풀어보자.
우선 물이 먼저 어떻게 번지는지 BFS를 통해 맵에 기록해둔다.
그 후 고슴도치가 움직이는데 물이 먼저 도착했는 곳인지 확인하며 BFS를 돌린다.
그렇게 하여 동굴에 도착할 수 있는지 판별하여 정답을 구할 수 있다.
소스 코드 :
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 120 121 122 123 124 125 | #include <iostream> #include <cstdio> #include <queue> #include <vector> using namespace std; typedef pair<int, int> pii; char arr[102][102]; int dy[4] = { -1,0,1,0 }; int dx[4] = { 0,-1,0,1 }; int water[102][102]; int mole[102][102]; bool check(int y, int x, int n, int m) { if ((0 <= y && y < n) && (0 <= x && x < m) && arr[y][x] != 'X') return true; return false; } int main() { int n, m; scanf("%d %d", &n, &m); for (int i = 0; i < n; i++) scanf("%s", arr[i]); queue<pair<pii, int> > q; for (int i = 0; i < n; i++) for (int j = 0; j < m; j++) if (arr[i][j] == '*') q.push({ { i,j }, 0 }); // 초기화 for (int i = 0; i < n; i++) for (int j = 0; j < m; j++) { water[i][j] = -1; mole[i][j] = -1; } while (!q.empty()) { int y = q.front().first.first; int x = q.front().first.second; int time = q.front().second; q.pop(); if (water[y][x] != -1) continue; water[y][x] = time; for (int i = 0; i < 4; i++) { int ny = y + dy[i]; int nx = x + dx[i]; if (!check(ny, nx, n, m) || arr[ny][nx] == 'D') continue; q.push({ {ny,nx},time + 1 }); } } int sy = -1, sx = -1; for (int i = 0; i < n; i++) for (int j = 0; j < m; j++) { if (arr[i][j] == 'S') { q.push({ { i,j }, 0 }); } else if (arr[i][j] == 'D') { sy = i; sx = j; } } while (!q.empty()) { int y = q.front().first.first; int x = q.front().first.second; int time = q.front().second; q.pop(); if (mole[y][x] != -1 || (mole[y][x] >= water[y][x] && water[y][x] != -1)) continue; mole[y][x] = time; for (int i = 0; i < 4; i++) { int ny = y + dy[i]; int nx = x + dx[i]; if (!check(ny, nx, n, m)) continue; if (time + 1 >= water[ny][nx] && water[ny][nx] != -1) continue; q.push({ {ny,nx}, time + 1 }); } } if (mole[sy][sx] != -1) printf("%d", mole[sy][sx]); else printf("KAKTUS"); return 0; } // This source code Copyright belongs to Crocus // If you want to see more? click here >> | Crocus |
반응형
'Applied > 알고리즘 문제풀이' 카테고리의 다른 글
[2667번] 단지번호붙이기 (0) | 2018.01.24 |
---|---|
[12913번] 매직 포션 (0) | 2018.01.23 |
[7453번] 합이 0인 네 정수 (0) | 2018.01.21 |
[13199번] 치킨 먹고 싶다 (0) | 2018.01.21 |
[1854번] K번째 최단경로 찾기 (0) | 2018.01.20 |