상세 컨텐츠

λ³Έλ¬Έ 제λͺ©

[BOJ] 7576: ν† λ§ˆν†  (C++)

PROGRAMMING/Algorithm

by koharin 2024. 3. 5. 01:14

λ³Έλ¬Έ

728x90
λ°˜μ‘ν˜•

πŸ” 문제 ν•΄κ²° 방법

λ¨Όμ € 읡은 ν† λ§ˆν† λŠ” λͺ¨λ‘ 큐에 λ„£μ–΄ λ†“λŠ”λ‹€.

이후 BFS둜 탐색을 ν•˜λ©΄μ„œ, 읡은 ν† λ§ˆν† μ™€ μΈμ ‘ν•œ ν† λ§ˆν†  쀑 아직 μ•ˆ 읡은 ν† λ§ˆν† (0)κ°€ 있으면,

읡은 ν† λ§ˆν† μ™€ μΈμ ‘ν•œ ν† λ§ˆν† λŠ” ν•˜λ£¨ μ§€λ‚œ ν›„ 읡게 λ˜λ―€λ‘œ 읡은 ν† λ§ˆν† μ™€ μΈμ ‘ν•œ ν† λ§ˆν†  = 읡은 ν† λ§ˆν†  읡은 λ‚  + 1 λ₯Ό ν•œλ‹€. 

이후 읡은 ν† λ§ˆν† λ₯Ό 큐에 λ„£μ–΄μ„œ λ‹€μŒ μΈμ ‘ν•œ ν† λ§ˆν†  쀑 μ•ˆ 읡은 ν† λ§ˆν† λ₯Ό κ΅¬ν•œλ‹€.

main ν•¨μˆ˜λ‘œ 리턴 ν›„, 읡은 ν† λ§ˆν† λŠ” λͺ¨λ‘ 1 μ΄μƒμ˜ 값을 κ°€μ§€λ―€λ‘œ ν•˜λ‚˜λΌλ„ 0인 ν† λ§ˆν† κ°€ 있으면 -1을 좜λ ₯ν•˜κ³  λ¦¬ν„΄ν•œλ‹€.

μ—†λ‹€λ©΄, λͺ¨λ“  읡은 ν† λ§ˆν†  쀑 κ°€μž₯ λ§ˆμ§€λ§‰μ— 읡은 ν† λ§ˆν† μ— μžˆλŠ” 값을 좜λ ₯ν•˜μ—¬ λͺ¨λ“  ν† λ§ˆν† κ°€ 읡을 수 μžˆλŠ” μ΅œμ†Œ λ‚ μ§œλ₯Ό κ΅¬ν•œλ‹€.

 

πŸ” DoubleFree 였λ₯˜ 문제 ν•΄κ²°

μ‚¬μ†Œν•œ μ‹€μˆ˜λ‘œ 인해..

int search() ν–ˆλŠ”λ° 리턴을 μ•ˆ ν•΄μ„œ λ°œμƒν–ˆλ‹€.

void search()둜 λ°”κΏ”μ„œ ν•΄κ²°.

 

πŸ’» 제좜 μ½”λ“œ

#include<iostream>
#include<vector>
#include<queue>
#include<algorithm>

using namespace std;

int M,N;
int nx[] = {1,0,-1,0};
int ny[] = {0,1,0,-1};

void search(queue< pair<int,int> > &q, vector< vector<int> > &tomato){

    while(!q.empty()){
        int cx = q.front().first;
        int cy = q.front().second;
        //cout << "visit (" << cx << "," << cy << "):" << tomato[cx][cy] << endl;
        q.pop();
        for(int i=0; i<4; i++){
            int next_x = cx + nx[i];
            int next_y = cy + ny[i];
            if(next_x < 0 || next_y < 0 || next_x >= N || next_y >= M) continue;
            if(tomato[next_x][next_y] == 0){
                // (cx,cy)와 μΈμ ‘ν•œ ν† λ§ˆνŠΈλŠ” (cx,cy)읡은 λ‚ μ§œ+1에 읡게 됨
                tomato[next_x][next_y] = tomato[cx][cy]+1;
                //cout << "visit (" << next_x << "," << next_y << "):" << tomato[next_x][next_y] << endl;
                q.push(make_pair(next_x,next_y));
            }
        }
    }
}

int main(){
    int max=0;
    cin >> M >> N;
    
    queue< pair<int, int> > q;
    vector< vector<int> > tomato(N, vector<int>(M,0));

    for(int i=0; i<N; i++){
        for(int j=0; j<M; j++){
            cin >> tomato[i][j];
            if(tomato[i][j]==1){ // 읡은 ν† λ§ˆν† λ₯Ό λͺ¨λ‘ 큐에 λ„£μŒ
                q.push(make_pair(i,j));
            }
        }
    }
    // BFS으둜 탐색
    search(q,tomato);

    for(int i=0; i<N; i++){
        for(int j=0; j<M; j++){
            if(tomato[i][j] == 0) {
                // μ•ˆ 읡은 ν† λ§ˆν†  ν•˜λ‚˜λΌλ„ 있으면 -1 좜λ ₯ ν›„ 리턴
                cout << "-1" << endl;
                return 0;
            }
            // λͺ¨λ“  ν† λ§ˆν†  μ΅λŠ”λ° κ±Έλ¦¬λŠ” μ‹œκ°„ κ΅¬ν•˜κΈ° μœ„ν•΄
            if(tomato[i][j] > max) max = tomato[i][j];
        }
    }
    // 처음 읡은 ν† λ§ˆν†  인근 ν† λ§ˆν† μ˜ μ΅λŠ” λ‚ μ§œκ°€ 1이 μ•„λ‹Œ μ΅μ€ν† λ§ˆν† (1)+1둜 κ³„μ‚°λ˜μ—ˆμœΌλ―€λ‘œ 1을 빼쀌
    cout << max-1 << endl;

    return 0;
}

728x90
λ°˜μ‘ν˜•

κ΄€λ ¨κΈ€ 더보기