dlehdanakf / Codingtest-Study

알고리즘 코딩테스트 토막지식 정리
1 stars 0 forks source link

Dijkstra Algorithm #5

Open dlehdanakf opened 3 years ago

dlehdanakf commented 3 years ago

개요

예제

배달

다익스트라 알고리즘

function solution(N, road, K) {
    const nodes = new Array(N + 1).fill(Infinity);
    nodes[0] = nodes[1] = 0;

    const traverse = (_n, _w) => {
        nodes[_n] = _w;
        road
            .filter(([n1, n2]) => n1 === _n || n2 === _n)
            .map(([n1, n2, w]) => n1 === _n ? [n2, w] : [n1, w])
            .forEach(([n, w]) => {
                if(_w + w < nodes[n]) {
                    traverse(n, _w + w);
                }
            });
    };

    traverse(1, 0);
    return nodes.filter(e => e <= K).length - 1;
}
dlehdanakf commented 3 years ago

가장 먼 노드

해결과정

function solution(n, edge) {
    const nodes = new Array(n + 1).fill(n + 1);
    const map = new Array(n + 1).fill(null).map(_ => []);
    nodes[0] = nodes[1] = 0;
    edge.forEach(([a,b]) => { map[a].push(b), map[b].push(a) });

    let arr = new Set([1]), weight = 1, answer = 0;
    while(true) {
        arr = new Set([...arr].map(e => map[e]).flat().filter(e => weight < nodes[e]));
        if(arr.size === 0) {
            return answer;
        }

        arr.forEach(e => nodes[e] = weight);
        answer = arr.size;
        weight += 1;
    }
}