#include <iostream>
#include <vector>
using namespace std;
int N, M;
int board[101][101];
bool visited[101][101];
int dx[] = {0, 0, 1, -1};
int dy[] = {1, -1, 0, 0};
// Step 2: 외부 공기를 탐색하는 DFS
// (0,0)에서 시작하여 치즈(1)를 만나기 전까지의 모든 0을 방문 표시함
void findOutsideAir(int x, int y) {
visited[x][y] = true;
for (int i = 0; i < 4; i++) {
int nx = x + dx[i];
int ny = y + dy[i];
if (nx >= 0 && nx < N && ny >= 0 && ny < M) {
// 방문하지 않았고, 치즈(1)가 아닌 빈 공간(0)만 이동
if (!visited[nx][ny] && board[nx][ny] == 0) {
findOutsideAir(nx, ny);
}
}
}
}
// void findOutsideAir(int x, int y) {
// visited[x][y] = true;
// for (int i = 0; i < 4; i++) {
// int nx = x + dx[i];
// int ny = y + dy[i];
// // 1. 격자 범위를 벗어나면 스킵
// if (nx < 0 || nx >= N || ny < 0 || ny >= M) continue;
// // 2. 이미 방문했거나, 치즈(1)인 칸이면 스킵
// if (visited[nx][ny] || board[nx][ny] == 1) continue;
// // 3. 위 조건들을 모두 통과한 경우(빈 공간이면서 미방문) 탐색 진행
// findOutsideAir(nx, ny);
// }
// }
int main() {
cin >> N >> M;
int totalCheese = 0;
for (int i = 0; i < N; i++) {
for (int j = 0; j < M; j++) {
cin >> board[i][j];
if (board[i][j] == 1) totalCheese++;
}
}
int time = 0;
int lastCheeseCount = 0;
// Step 5: 메인 루프 (치즈가 다 녹을 때까지 반복)
while (totalCheese > 0) {
// 매 시간마다 방문 배열 초기화
for (int i = 0; i < N; i++) {
for (int j = 0; j < M; j++) visited[i][j] = false;
}
lastCheeseCount = totalCheese; // 녹기 직전 치_즈 개수 저장
// 1. 외부 공기 파악 (Step 2)
findOutsideAir(0, 0);
// 2. 녹을 치즈 선별 (Step 3)
vector<pair<int, int>> meltList;
for (int i = 0; i < N; i++) {
for (int j = 0; j < M; j++) {
if (board[i][j] == 1) {
bool canMelt = false;
for (int k = 0; k < 4; k++) {
int ni = i + dx[k];
int nj = j + dy[k];
// 주변에 '방문된 빈 공간(외부 공기)'이 있다면 녹음
if (visited[ni][nj]) {
canMelt = true;
break;
}
}
if (canMelt) meltList.push_back({i, j});
}
}
}
// 3. 치즈 녹이기 (Step 4)
for (auto curr : meltList) {
if (board[curr.first][curr.second] == 1) {
board[curr.first][curr.second] = 0;
totalCheese--;
}
}
time++;
}
cout << time << "\n" << lastCheeseCount << "\n";
return 0;
}
To embed this project on your website, copy the following code and paste it into your website's HTML: