[λ°±μ€] 7576 ν λ§ν BFS
λ¬Έμ :
https://www.acmicpc.net/problem/7576
7576λ²: ν λ§ν
첫 μ€μλ μμμ ν¬κΈ°λ₯Ό λνλ΄λ λ μ μ M,Nμ΄ μ£Όμ΄μ§λ€. Mμ μμμ κ°λ‘ μΉΈμ μ, Nμ μμμ μΈλ‘ μΉΈμ μλ₯Ό λνλΈλ€. λ¨, 2 ≤ M,N ≤ 1,000 μ΄λ€. λμ§Έ μ€λΆν°λ νλμ μμμ μ μ₯λ ν λ§ν
www.acmicpc.net
λΆμ :
μ΄λ°μμΌλ‘ ν λ§ν λμ₯μ΄ μ‘΄μ¬ ν λ
1μ μ΅μ ν λ§ν , μ μ 0μ μ΅μ§ μμ ν λ§ν , μ μ -1μ ν λ§ν κ° λ€μ΄μμ§ μμ μΉΈ
μ μλ―Ένλ€.
μ΅μ ν λ§ν μ€μ¬μΌλ‘ μνμ’μ°λ‘ ν루λ§λ€ ν λ§ν κ° μ΅λλ° λͺμΌμ΄λ©΄ λμ₯ λ΄ λͺ¨λ ν λ§ν κ° μ΅λμ§ λ μ§λ₯Ό μΆλ ₯νλ λ¬Έμ μλ€.
μ°μ ν λ§ν λμ₯μ νμνλ€λ μ μμ BFS, DFSλ‘ μ κ·Όν΄μΌ νλ€ μκ°νκ³ νμμ νλ©΄μ λ°©λ¬Ένμ§ μμλ 0μ forλ¬Έμ λλ©΄μ 1μ© λλ € μ£Όκ³ λͺ¨λ 0μ΄ 1λ‘ λ°λμμλ dfs νμμ ν΅ν΄ λ μ§λ₯Ό κ³μ°νλλ‘ νμλ€.
//
// 7576_tomato.cpp
// SOMAπ©π»π»
//
// Created by JoSoJeong on 2021/04/22.
//
#include <stdio.h>
#include <queue>
#include <iostream>
using namespace std;
int tomatoMap[1001][1001];
int M, N;
int tomatoCount;
int dfscount;
int visit[1001][1001] = {false, };
int dx[] = { 0, 0, 1, -1 }; //up down left right
int dy[] = { 1, -1, 0, 0 };
queue<pair<int, int>> s;
void tomato_dfs(){
while(!s.empty()){
pair<int, int> cur = s.front();
s.pop();
for(int i = 0; i < 4; i++){
int nextX = cur.first + dx[i];
int nextY = cur.second + dy[i];
if(nextX < N && nextY < M && nextX >= 0 && nextY >= 0 ){
if(visit[nextX][nextY] == false && tomatoMap[nextX][nextY] == 0){
visit[nextX][nextY] = true;
s.push({nextX, nextY});
dfscount++;
tomatoMap[nextX][nextY] = tomatoMap[cur.first][cur.second] + 1;
}
}
}
}
}
int main(){
cin >> M >> N; // 6 4
for(int i = 0; i < N; i++){
for(int j = 0; j < M; j++){
cin >> tomatoMap[i][j];
if(tomatoMap[i][j] == 0){ // tomato count
tomatoCount++;
}else if(tomatoMap[i][j] == 1){
s.push({i,j});
//startPoint = make_pair(i,j);
}
}
}
int max = 0;
if(tomatoCount == 0){
cout << "0" << '\n'; // λͺ¨λ ν λ§ν μ΅μ΄μλ μν
return 0;
}else{
tomato_dfs();
if(tomatoCount - dfscount != 0){ // ν λ§ν λ€ μ΅μ§ x
cout << "-1" << '\n';
return 0;
}
for(int i = 0; i < N; i++){ // ν λ§ν λ€ μ΅ν
for(int j = 0; j < M; j++){
if(max < tomatoMap[i][j]){
max = tomatoMap[i][j];
}
}
}
cout << max - 1 << '\n';
}
return 0;
}
λ§μ§λ§ ν λ§ν μ΅μ λ μ§λ₯Ό ꡬνκΈ° μν΄ μ΄μ€ forλ¬ΈμΌλ‘ max κ°μ μ°Ύλ λΆλΆμ΄ λΉν¨μ¨μ μΌλ‘ 보μΈλ€. μ΄λΆλΆμ μμ ν΄λ³΄μμΌκ² λ€.