๐ก ๊ธฐ์กด ๋ธ๋ญ ์ ์ธ๊ธฐ ์ฝ๋์ ์ผ์ ๋ น์ด๋ ์ฝ๋๋ฅผ ์ถ๊ฐํด ํ์๋ค.
์ฝ๋
const fs = require('fs');
let input = fs.readFileSync('/dev/stdin').toString().trim().split('\n');
const [N, M] = input.shift().split(" ").map(Number);
input = input.map((el) => el.split(" ").map(Number));
const dir = [
[0, 1],
[0, -1],
[1, 0],
[-1, 0],
];
let visited;
let minus = Array.from(new Array(N), () => new Array(M).fill(0));
const bfs = (y, x) => {
const queue = [[y, x]];
visited[y][x] = true;
while (queue.length) {
const [locY, locX] = queue.shift();
for (let d = 0; d < 4; d++) {
const nextLocY = locY + dir[d][0];
const nextLocX = locX + dir[d][1];
if (
nextLocY <= 0 ||
nextLocX <= 0 ||
nextLocY >= N - 1 ||
nextLocX >= M - 1
)
continue;
if (visited[nextLocY][nextLocX]) continue;
if (input[nextLocY][nextLocX]) {
queue.push([nextLocY, nextLocX]);
visited[nextLocY][nextLocX] = true;
}
}
}
};
const meltingIce = () => {
for (let i = 1; i < N - 1; i++) {
for (let j = 1; j < M - 1; j++) {
if (input[i][j]) {
for (let d = 0; d < 4; d++) {
const nextI = i + dir[d][0];
const nextJ = j + dir[d][1];
if (nextI < 0 || nextJ < 0 || nextI >= N || nextJ >= M) continue;
if (!input[nextI][nextJ]) minus[i][j]--;
}
}
}
}
};
let year = 0;
while (true) {
let block = 0;
visited = Array.from(new Array(N), () => new Array(M).fill(false));
for (let i = 1; i < N - 1; i++) {
for (let j = 1; j < M - 1; j++) {
if (!visited[i][j] && input[i][j]) {
bfs(i, j);
block++;
}
}
}
if (block >= 2) return console.log(year);
if (!block) return console.log(0);
minus = Array.from(new Array(N), () => new Array(M).fill(0));
meltingIce();
for (let i = 1; i < N - 1; i++) {
for (let j = 1; j < M - 1; j++) {
input[i][j] += minus[i][j];
if (input[i][j] < 0) input[i][j] = 0;
}
}
year++;
}