๋ณธ๋ฌธ ๋ฐ”๋กœ๊ฐ€๊ธฐ
๐Ÿš“ Self Study/๐Ÿ”“ BaekJoon

๋ฐฑ์ค€ BaekJoon (ํ† ๋งˆํ† , 7569๋ฒˆ) C++

by UKHYUN22 2022. 1. 11.
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;
}