https://school.programmers.co.kr/learn/courses/30/lessons/154540
function solution(maps) {
const answer = [],
[row, col] = [maps.length, maps[0].length],
[dirX, dirY] = [[0, 0, -1, 1], [-1, 1, 0, 0]],
visited = Array.from(Array(row),() => new Array(col).fill(false));
const dfs = (x, y) => {
let food = maps[x][y] * 1;
visited[x][y] = true;
for (let i = 0; i < 4; ++i) {
const [destX, destY] = [x + dirX[i], y + dirY[i]];
if (destX < 0 || destX >= row || destY < 0 || destY >= col) continue;
if (isNaN(maps[destX][destY]) || visited[destX][destY]) continue;
food += dfs(destX, destY);
}
return food;
};
maps.forEach((map, x) => {
[...map].forEach((el, y) => {
if (isNaN(el) || visited[x][y]) return;
answer.push(dfs(x, y));
});
});
return answer.length ? answer.sort((a, b) => a - b) : [-1];
}
'Coding Test > Programmers' 카테고리의 다른 글
[Programmers] (2019 KAKAO BLIND RECRUITMENT) Lv 2. 후보키 (0) | 2023.03.28 |
---|---|
[Programmers] (재귀) Lv 2. 하노이의 탑 (0) | 2023.03.28 |
[Programmers] (2020 KAKAO BLIND RECRUITMENT) Lv 2. 문자열 압축 (0) | 2023.03.26 |
[Programmers] (Summer/Winter Coding(2019)) Lv 2. 멀쩡한 사각형 (0) | 2023.03.24 |
[Programmers] (2021 카카오 채용연계형 인턴십) Lv 2. 거리두기 확인하기 (1) | 2023.03.23 |
댓글