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 | #include <stdio.h> #include <queue> #include <utility> using namespace std; queue<pair<pair<int, int>, pair<int, int>>> q; // (date, h), (y,x) int dx[6] = {1,-1,0,0,0,0}; int dy[6] = {0,0,1,-1,0,0}; int dh[6] = {0,0,0,0,1,-1}; int arr[105][105][105] = { 0 }; int chk[105][105][105] = { 0 }; void bfs(int col, int row, int height, int sum) { int cnt = 0, len; while (!q.empty()) { len = q.front().first.first; int h = q.front().first.second; int y = q.front().second.first; int x = q.front().second.second; chk[h][y][x] = 1; q.pop(); for (int i = 0; i < 6; i++) { int hh = h + dh[i]; int xx = x + dx[i]; int yy = y + dy[i]; if (hh < 0 || hh >= height || xx < 0 || xx >= col || yy < 0 || yy >= row) continue; if (chk[hh][yy][xx] == 1 || arr[hh][yy][xx] != 0) continue; chk[hh][yy][xx] = 1; q.push(make_pair(make_pair(len + 1, hh), make_pair(yy, xx))); cnt++; } } if (cnt == 0) printf("0"); else if (cnt == sum) printf("%d", len); else printf("-1"); } int main() { int col, row, h; scanf("%d %d %d", &col, &row, &h); int hidx = 0, sum = 0; for (int i = 0; i < row * h; i++) { int y = i % row; int hidx = i / row; for (int x = 0; x < col; x++) { scanf("%d", &arr[hidx][y][x]); if (arr[hidx][y][x] == 0) sum++; else if(arr[hidx][y][x] == 1){ q.push(make_pair(make_pair(0,hidx), make_pair(y, x))); chk[hidx][y][x] = 1; } } } bfs(col, row, h, sum); } | cs |
7576 토마토의 업그레이드 버전이나, 알고리즘은 동일하다
맨 처음에 입력 값을 height에 맞게 받아들이는 것이 어렵다.
이 부분에서 시간이 좀 걸렸으나, 다른 부분은 알고리즘이 동일했기 때문에 구현을 조금만 신경써도 됐다.
'알고리즘 > BFS' 카테고리의 다른 글
2644 촌수계산 (0) | 2020.01.18 |
---|---|
2146 다리만들기 (0) | 2020.01.18 |
1697 숨바꼭질 (0) | 2020.01.14 |
7562 나이트의 이동 (0) | 2020.01.14 |
7576 토마토 (0) | 2020.01.14 |