본문 바로가기
Coding Test/Programmers

[Programmers] Lv 2. 무인도 여행

by song.ift 2023. 3. 28.

https://school.programmers.co.kr/learn/courses/30/lessons/154540

 

프로그래머스

코드 중심의 개발자 채용. 스택 기반의 포지션 매칭. 프로그래머스의 개발자 맞춤형 프로필을 등록하고, 나와 기술 궁합이 잘 맞는 기업들을 매칭 받으세요.

programmers.co.kr

 

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];
}

GitHub : https://github.com/developeSHG/Algorithm-Baekjoon_Programmers/tree/main/%ED%94%84%EB%A1%9C%EA%B7%B8%EB%9E%98%EB%A8%B8%EC%8A%A4/unrated/154540.%E2%80%85%EB%AC%B4%EC%9D%B8%EB%8F%84%E2%80%85%EC%97%AC%ED%96%89

 

GitHub - developeSHG/Algorithm-Baekjoon_Programmers: 백준 and 프로그래머스 소스코드

백준 and 프로그래머스 소스코드. Contribute to developeSHG/Algorithm-Baekjoon_Programmers development by creating an account on GitHub.

github.com

 

댓글