https://www.acmicpc.net/problem/7576
7576번: 토마토
첫 줄에는 상자의 크기를 나타내는 두 정수 M,N이 주어진다. M은 상자의 가로 칸의 수, N은 상자의 세로 칸의 수를 나타낸다. 단, 2 ≤ M,N ≤ 1,000 이다. 둘째 줄부터는 하나의 상자에 저장된 토마토
www.acmicpc.net
📌 작성한 코드
// 7576
const fs = require("fs");
const filePath = process.platform === "linux" ? "/dev/stdin" : "Beakjoon/Gold/test.txt";
let input = fs.readFileSync(filePath).toString().trim().split("\n");
const [M, N] = input.shift().split(" ").map(Number);
let remains = 0;
const tomatoes = [];
for (let i = 0; i < N; i++) {
const temp = input.shift().split(" ").map(Number);
tomatoes.push(temp);
remains += temp.filter((item) => item === 0).length;
}
const startTomatoes = [];
for (let i = 0; i < N; i++) {
for (let j = 0; j < M; j++) {
if (tomatoes[i][j] === 1) {
startTomatoes.push([i, j, 1]);
}
}
}
const dx = [1, -1, 0, 0];
const dy = [0, 0, 1, -1];
const solution = () => {
const bfs = () => {
const queue = [...startTomatoes];
let idx = 0;
while (queue.length > idx) {
const [x, y, d] = queue[idx++];
tomatoes[x][y] = d;
for (let i = 0; i < 4; i++) {
const nx = x + dx[i];
const ny = y + dy[i];
if (nx < 0 || nx >= N || ny < 0 || ny >= M) continue;
if (tomatoes[nx][ny] === 0) {
tomatoes[nx][ny] = d + 1;
queue.push([nx, ny, d + 1]);
remains--;
}
}
if (remains <= 0) return queue[queue.length - 1][2];
}
return queue[queue.length - 1][2];
};
if (startTomatoes.length === 0) return console.log(-1);
const answer = bfs() - 1;
remains > 0 ? console.log(-1) : console.log(answer);
};
solution();
📌 풀이
풀이는 이전에 푼 토마토(더 어려운 버전) 참고하기! 거의 똑같은 문제이고 H에 대한 부분만 제외하고 풀면 지금 문제와 똑같다.
https://youme016.tistory.com/226
[JavaScript/BFS] 백준 골드 5 : 7569 - 토마토
https://www.acmicpc.net/problem/7569 7569번: 토마토 첫 줄에는 상자의 크기를 나타내는 두 정수 M,N과 쌓아올려지는 상자의 수를 나타내는 H가 주어진다. M은 상자의 가로 칸의 수, N은 상자의 세로 칸의 수
youme016.tistory.com
알고리즘 공부를 다시 시작하면서 풀어본 문제였는데 어렵지 않게 풀 수 있었다. 그러나 런타임 에러(TypeError)가 발생해서 해결하는데 애를 먹었다. 해당 문제에서 런타임 에러가 발생한 이유는 익은 토마토가 하나도 없는 경우에는 bfs에서 queue가 비어있게 되는데 return값으로 queue에 접근하려고 해서 문제가 발생하는 것이다. 그래서 bfs 작동시키기 전에 미리 확인하고, 익은 토마토가 하나도 없다면 바로 -1을 출력할 수 있게 다음 코드를 추가해주었다.
if (startTomatoes.length === 0) return console.log(-1);
✅ 성공

'알고리즘 > 백준' 카테고리의 다른 글
| [JavaScript/BFS] 백준 실버 1 : 7562 - 나이트의 이동 (0) | 2024.01.12 |
|---|---|
| [JavaScript/DFS] 백준 골드 5 : 10026 - 적록색약 (2) | 2024.01.11 |
| [JavaScript/DFS] 백준 실버 2 : 1012 - 유기농 배추 (0) | 2024.01.08 |
| [JavaScript/BFS] 백준 실버 1 : 1926번 - 그림 (0) | 2023.10.10 |
| [JavaScript/DFS] 백준 골드 4 : 2573번 - 빙산 (0) | 2023.09.22 |