๐งธ 3์ฐจ์๋ฐฐ์ด์ด๋ผ ๋ง์ด ํท๊ฐ๋ ธ๋ค.. ์๊ฐ์ด๊ณผ๋ก๋ ๊ณ ์ํ๋ค..
๐ ์ฒ์์ ์ต์ ํ ๋งํ ๋ค์ด ํ๋ฒ์ ํ์์ ์์ํด์ผํ๋๋ฐ ์ด๋ป๊ฒํ ๊น ๊ณ ๋ฏผ์ ํ๋ค ๊ฒฐ๊ตญ ๋ต์ ํ์ธํด๋ดค๋ค.
๐ก ์ ๋ง ๊ฐ๋จํ ๋ฐฉ๋ฒ์ด์๋ค. ์ฒ์์ ํ์ ๋ฃ์ด์ฃผ๊ณ ์์ํ๊ธฐ..! ์ ์ด๊ฑธ ์๊ฐ์ ๋ชปํ์๊น๐ข
๐ ์๊ฐ์ด๊ณผ๊ฐ ๋ฐ์ํ๋ค.
๐ก queue๋ฅผ ์ฒ๋ฆฌํ ๋ shift()๊ฐ ์๋ index๋ฅผ ํ๋์ฉ ๋๋ ค์ฃผ๋ฉด์ ํด์ผํ๋ค. ์ด๋ฐ ๋ฐฉ๋ฒ๋ ์๊ตฌ๋๋ฅผ ๊นจ๋ฌ์๋ค...
์ฝ๋
const fs = require('fs');
const input = fs.readFileSync('/dev/stdin').toString().trim().split("\n")
.map((item) => item.split(" ").map(Number));
const [M, N, H] = input.shift();
const boxes = Array.from(new Array(H), () => []);
const queue = [];
for (let h = 0; h < H; h++) {
for (let n = 0; n < N; n++) {
boxes[h].push(input[n + h * N]);
input[n + h * N].forEach((num, index) => {
if (num === 1) {
queue.push([h, n, index, 1]);
}
});
}
}
const dir = [
[0, 0, 1],
[0, 0, -1],
[0, 1, 0],
[0, -1, 0],
[1, 0, 0],
[-1, 0, 0],
];
let index = 0;
const BFS = () => {
while (index <= queue.length - 1) {
const [ph, pn, pm, day] = queue[index];
index++;
for (let d = 0; d < 6; d++) {
const nh = ph + dir[d][0];
const nn = pn + dir[d][1];
const nm = pm + dir[d][2];
if (
nh >= 0 &&
nn >= 0 &&
nm >= 0 &&
nh < H &&
nn < N &&
nm < M &&
boxes[nh][nn][nm] === 0
) {
queue.push([nh, nn, nm, day + 1]);
boxes[nh][nn][nm] = day + 1;
}
}
}
};
BFS();
let result = 0;
for (let h = 0; h < H; h++) {
for (let n = 0; n < N; n++) {
for (let m = 0; m < M; m++) {
if (boxes[h][n][m] === 0) {
return console.log(-1);
} else {
if (result < boxes[h][n][m]) {
result = boxes[h][n][m];
}
}
}
}
}
console.log(result - 1);