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 | #include <stdio.h> #include <queue> #include <utility> using namespace std; queue<pair<int, pair<int, int>>> q; int arr[1005][1005] = { 0 }; int chk[1005][1005] = { 0 }; int dx[4] = { 1,-1, 0,0 }; int dy[4] = { 0,0,1,-1 }; int bfs(int sum, int endY, int endX) { int rst = 0, len; while (!q.empty()) { len = q.front().first; int y = q.front().second.first; int x = q.front().second.second; q.pop(); for (int i = 0; i < 4; i++) { int xx = x + dx[i]; int yy = y + dy[i]; if (1 > xx || xx > endX || 1 > yy || yy > endY) continue; if (chk[yy][xx] == 1 || arr[yy][xx] == -1) continue; chk[yy][xx] = 1; rst++; q.push(make_pair(len + 1, make_pair(yy, xx))); } } if (sum == rst) return len; else return -1; } int main() { int y, x; scanf("%d %d", &x, &y); int sum = y * x; for (int i = 1; i <= y; i++) { for (int j = 1; j <= x; j++) { scanf("%d", &arr[i][j]); if (arr[i][j] == 1) { q.push(make_pair(0, make_pair(i, j))); chk[i][j] = 1; sum--; } else if (arr[i][j] == -1) { sum--; } } } printf("%d",bfs(sum, y, x)); } | cs |
미로찾기 문제를 조금 더 심화한 내용의 문제였다.
시작하는 지점이 한 개가 아니라 여러 곳일때 어떻게 처리해야 하는지 고민했으며,
끝 부분 처리를 어떻게 할지 고민하다가 그냥 while 문의 queue 가 다 비워질때까지 하는 걸로 처리했다.
미로찾기도 이런 식으로 처리했는게 가능할 것 같지만, 다른점은
1. 미로찾기의 경우엔 출구가 정해져 있지만
2. 토마토 문제의 경우, 출구가 따로 정해진 것이 아니라 계속 흘러가기만 하는 형식이라는 것.
풀이가 다를 수밖에 없다.
'알고리즘 > BFS' 카테고리의 다른 글
1697 숨바꼭질 (0) | 2020.01.14 |
---|---|
7562 나이트의 이동 (0) | 2020.01.14 |
2178 미로 탐색 (0) | 2020.01.13 |
말과 기사 더블릿 (0) | 2019.02.25 |
댐 더블릿 (0) | 2019.02.23 |