λ¨Όμ μ΅μ ν λ§ν λ λͺ¨λ νμ λ£μ΄ λλλ€.
μ΄ν BFSλ‘ νμμ νλ©΄μ, μ΅μ ν λ§ν μ μΈμ ν ν λ§ν μ€ μμ§ μ μ΅μ ν λ§ν (0)κ° μμΌλ©΄,
μ΅μ ν λ§ν μ μΈμ ν ν λ§ν λ ν루 μ§λ ν μ΅κ² λλ―λ‘ μ΅μ ν λ§ν μ μΈμ ν ν λ§ν = μ΅μ ν λ§ν μ΅μ λ + 1 λ₯Ό νλ€.
μ΄ν μ΅μ ν λ§ν λ₯Ό νμ λ£μ΄μ λ€μ μΈμ ν ν λ§ν μ€ μ μ΅μ ν λ§ν λ₯Ό ꡬνλ€.
main ν¨μλ‘ λ¦¬ν΄ ν, μ΅μ ν λ§ν λ λͺ¨λ 1 μ΄μμ κ°μ κ°μ§λ―λ‘ νλλΌλ 0μΈ ν λ§ν κ° μμΌλ©΄ -1μ μΆλ ₯νκ³ λ¦¬ν΄νλ€.
μλ€λ©΄, λͺ¨λ μ΅μ ν λ§ν μ€ κ°μ₯ λ§μ§λ§μ μ΅μ ν λ§ν μ μλ κ°μ μΆλ ₯νμ¬ λͺ¨λ ν λ§ν κ° μ΅μ μ μλ μ΅μ λ μ§λ₯Ό ꡬνλ€.
μ¬μν μ€μλ‘ μΈν΄..
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;
}
[BOJ] 14501: ν΄μ¬ (C++) (0) | 2024.03.24 |
---|---|
[Softeer] [HSAT 7ν μ κΈ° μ½λ© μΈμ¦νκ° κΈ°μΆ] μμλλ‘ λ°©λ¬ΈνκΈ° (C++) (0) | 2024.02.25 |
[BOJ] 2875 (C++) (1) | 2024.02.25 |
[Softeer] μλμ°¨ ν μ€νΈ (C++) (0) | 2024.02.16 |
[Softeer] μ±μ νκ· (C++) (0) | 2024.02.15 |