[JavaScript] 프로그래머스 가장 먼 노드 LEVEL3

문제풀이

JS Map 객체를 사용한 풀이

const bfs = (graph, start, n) => {
    let visit = new Array(n).fill(false);
    let queue = [];
    let arr = [];
    
    visit.push(start);
    queue.push([start, 0]);
    
    while (queue.length > 0) {
        const [node, cnt] = queue.shift();
        const values = graph.get(node);
        
        for (const value of values) {
            if (!visit.includes(value)) {
                visit.push(value);
                queue.push([value, cnt + 1]);
                arr.push(cnt + 1);
            }
        }
    }
    
    let max = Math.max(...arr);
    let answer = 0;
    for (const cnt of arr) {
        if (max === cnt) answer++;
    }
    return answer;
}

function solution(n, edge) {
    let graph = new Map();
    
    for(let [a, b] of edge) {
        graph.get(a)? graph.set(a, [...graph.get(a), b]) : graph.set(a, [b]);
        graph.get(b)? graph.set(b, [...graph.get(b), a]) : graph.set(b, [a]);
    }
    
    return bfs(graph, 1, n);
}

JS Object를 사용한 풀이

const bfs = (graph, start, n) => {
    let visit = new Array(n).fill(false);
    let queue = [];
    let arr = [];
    
    visit.push(start);
    queue.push([start, 0]);
    
    while (queue.length > 0) {
        const [node, cnt] = queue.shift();
        
        for (const value of graph[node]) {
            if (!visit.includes(value)) {
                visit.push(value);
                queue.push([value, cnt + 1]);
                arr.push(cnt + 1);
            }
        }
    }
    
    let max = Math.max(...arr);
    let answer = 0;
    for (const cnt of arr) {
        if (max === cnt) answer++;
    }
    return answer;
}

function solution(n, edge) {
    let graph = {};
    
    for (let [a, b] of edge) {
        graph[a] ? graph[a].push(b) : graph[a] = [b];
        graph[b] ? graph[b].push(a) : graph[b] = [a];
    }
    
    return bfs(graph, 1, n);
}

좋은 웹페이지 즐겨찾기