kakasoo

[node.js] 가장 먼 노드 ( 프로그래머스 레벨3 ) 본문

프로그래밍/알고리즘 풀이

[node.js] 가장 먼 노드 ( 프로그래머스 레벨3 )

카카수(kakasoo) 2021. 7. 2. 17:06
반응형
// 프로그래머스 레벨 3 가장 먼 노드를 풀었습니다.

const solution = (n, edge) => {
    const map = new Array(n + 1).fill(0);
    for (let i = 1; i < map.length; i++) {
        map[i] = [];
    }

    edge.forEach((el) => {
        const [from, to] = el;
        map[from].push(to);
        map[to].push(from);
    });

    const visited = new Array(n + 1).fill(0);
    visited[0] = -1;

    const bfs = (start) => {
        const queue = [start];
        visited[start] = 1;

        while (queue.length) {
            const cur = queue.shift();

            for (let i = 0; i < map[cur].length; i++) {
                const next = map[cur][i];

                if (!visited[next] || visited[next] > visited[cur] + 1) {
                    queue.push(next);
                    visited[next] = visited[cur] + 1;
                }
            }
        }
    };
    bfs(1);

    const maxValue = Math.max(...visited);
    return visited.filter((el) => el === maxValue).length;
};

그래프 문제는 항상 비슷한 코드로 작성되기 때문에 사실 레벨3이라기엔 쉽다.
어떤 모양의 맵을 만들고, bfs인지 dfs인지 결정하고,
visited를 어떻게 체크할 것인지,
전체 배열에 대해서 진행할 것인지, 아니면 특정한 점에서만 시작을 할 것인지 ( 이 문제는 1번 노드에서 출발했다. )

이러한 부분들만 결정해주면 된다.

반응형