728x90
queue를 이용한 bfs를 할 때 for문의 조건을 변하지 않는 값으로 먼저 할당하고 진행하자.
여기서는 int size = q.size(); 로 먼저 size를 고정시키고 for문을 돌려야 한다.
#include <iostream>
#include <vector>
#include <algorithm>
#include <queue>
using namespace std;
int arr[101][101][101];
int visited[101][101][101] = {0,};
int dim[6][3] = { {0,0,1}, {0,0,-1}, {0,1,0}, {0,-1,0}, {-1,0,0}, {1,0,0}};
int main() {
ios_base::sync_with_stdio(false); cin.tie(NULL);
int row = 0, col = 0, height =0;
queue<pair<pair<int,int>,int>> q;
cin >> col >> row >> height;
for(int h = 0 ; h < height ; h++) {
for(int i = 0 ; i < row ; i++) {
for(int j = 0 ; j < col ; j++) {
int num;
cin >> num;
if(num == 1) {
q.push({{i,j}, h});
}
arr[h][i][j] = num;
}
}
}
int count = 0;
while(!q.empty()) {
int size = q.size();
count++;
for(int j = 0 ; j < size ; j++) {
int d_row = q.front().first.first;
int d_col = q.front().first.second;
int d_height = q.front().second;
q.pop();
for(int i = 0 ; i < 6 ; i++) {
int n_row = d_row + dim[i][0];
int n_col = d_col + dim[i][1];
int n_height = d_height + dim[i][2];
if(n_row >= 0 && n_row < row && n_col >= 0 && n_col < col &&
n_height >= 0 && n_height < height && arr[n_height][n_row][n_col] == 0) {
arr[n_height][n_row][n_col] = 1;
q.push({{n_row,n_col}, n_height});
}
}
}
}
int none = 0;
for(int h = 0 ; h < height ; h++) {
for(int i = 0 ; i < row ; i++) {
for(int j = 0 ; j < col ; j++) {
if(arr[h][i][j] == 0)
none++;
}
}
}
if(none > 0) cout << "-1";
else cout << count-1;
return 0;
}
'🚓 Self Study > 🔓 BaekJoon' 카테고리의 다른 글
백준 BaekJoon (스타트링크, 5014번) C++ (0) | 2022.01.11 |
---|---|
백준 BaekJoon (숨바꼭질, 1697번) C++ (0) | 2022.01.11 |
백준 BaekJoon(촌수 계산, 2644번) C++ (0) | 2022.01.10 |
백준 BaekJoon (DFS와 BFS, 1260) C++ (0) | 2022.01.05 |
백준 BaekJoon (바이러스, 2606) C++ (0) | 2022.01.05 |