Algorithm/Programmers

[JavaScript] ํ”„๋กœ๊ทธ๋ž˜๋จธ์Šค - ๊ฐ€์žฅ ๋จผ ๋…ธ๋“œ

๊ฐœ๋ฐœ๊ฐœ๊ตด๐Ÿธ 2022. 8. 26. 19:01

[๋ฌธ์ œ]

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

 

ํ”„๋กœ๊ทธ๋ž˜๋จธ์Šค

์ฝ”๋“œ ์ค‘์‹ฌ์˜ ๊ฐœ๋ฐœ์ž ์ฑ„์šฉ. ์Šคํƒ ๊ธฐ๋ฐ˜์˜ ํฌ์ง€์…˜ ๋งค์นญ. ํ”„๋กœ๊ทธ๋ž˜๋จธ์Šค์˜ ๊ฐœ๋ฐœ์ž ๋งž์ถคํ˜• ํ”„๋กœํ•„์„ ๋“ฑ๋กํ•˜๊ณ , ๋‚˜์™€ ๊ธฐ์ˆ  ๊ถํ•ฉ์ด ์ž˜ ๋งž๋Š” ๊ธฐ์—…๋“ค์„ ๋งค์นญ ๋ฐ›์œผ์„ธ์š”.

programmers.co.kr

 

[ํ’€์ด]

๋…ธ๋“œ 1๋ถ€ํ„ฐ์˜ ์ตœ์†Œ ๊ฑฐ๋ฆฌ๋ฅผ ๋ชจ๋‘ ๊ตฌํ•ด์•ผ ํ•˜๊ธฐ ๋•Œ๋ฌธ์— BFS๋ฅผ ํ™œ์šฉํ•˜์˜€์Šต๋‹ˆ๋‹ค.

 

์ดˆ๊ธฐ ์„ธํŒ…

  • ์–‘๋ฐฉํ–ฅ ๊ทธ๋ž˜ํ”„ ์ •๋ณด๋ฅผ ์ €์žฅํ•˜๊ธฐ ์œ„ํ•ด ์ด์ฐจ์› ๋ฐฐ์—ด graph์— ์ •๋ณด๋ฅผ ์ €์žฅํ•˜์˜€์Šต๋‹ˆ๋‹ค.
  • ๋ฐฉ๋ฌธํ•œ ์ •์ ์„ ์ €์žฅํ•˜๋Š” visit๋ฐฐ์—ด์„ ์„ ์–ธํ•˜๊ณ  false๋กœ ์ดˆ๊ธฐํ™” ํ•ด์ฃผ์—ˆ์Šต๋‹ˆ๋‹ค.
  • ๋…ธ๋“œ 1๋ถ€ํ„ฐ์˜ ๊ฑฐ๋ฆฌ๋ฅผ ์ €์žฅํ•˜๋Š” dist ๋ฐฐ์—ด์„ ์„ ์–ธํ•˜๊ณ  0์œผ๋กœ ์ดˆ๊ธฐํ™” ํ•ด์ฃผ์—ˆ์Šต๋‹ˆ๋‹ค.
  • ๋…ธ๋“œ๋ฅผ ๋ฐฉ๋ฌธํ•˜๋ฉฐ ์ตœ๋Œ€ ๊ฑฐ๋ฆฌ max๋ฅผ ์ €์žฅํ•˜๊ธฐ ์œ„ํ•ด max๋ฅผ ์„ ์–ธํ•ฉ๋‹ˆ๋‹ค.

 

ํ๋ฅผ ํ™œ์šฉํ•ด ๊ทธ๋ž˜ํ”„๋ฅผ ํƒ์ƒ‰ํ•˜์˜€๋Š”๋ฐ, queue์—์„œ ์ •์  1๊ฐœ๋ฅผ shiftํ•˜์—ฌ ํ•ด๋‹น ์ •์ ๊ณผ ์—ฐ๊ฒฐ๋œ ์•„์ง ๋ฐฉ๋ฌธํ•˜์ง€ ์•Š์€ ์ •์ ๋“ค์„ ํƒ์ƒ‰ํ•˜๋ฉฐ ํ˜„์žฌ ์ •์ ์˜ dist์ •๋ณด + 1์„ ์ €์žฅํ•˜์˜€์Šต๋‹ˆ๋‹ค. ๊ทธ๋ž˜ํ”„๋ฅผ ํƒ์ƒ‰ํ•˜๋Š” ๊ณผ์ •์—์„œ ์ตœ๋Œ€ ๊ฑฐ๋ฆฌ max๋ฅผ ๊ฐฑ์‹ ํ•ด์ฃผ์—ˆ์Šต๋‹ˆ๋‹ค.

 

1์„ ๋ฝ‘์•„์„œ 2, 3 ๋ฐฉ๋ฌธ ํ›„, dist[2] = 1, dist[3] = 1

2๋ฅผ ๋ฝ‘์•„์„œ 4, 5 ๋ฐฉ๋ฌธ ํ›„, dist[4] = 2, dist[5] = 2

3์„ ๋ฝ‘์•„์„œ 6 ๋ฐฉ๋ฌธ ํ›„, dist[6] = 2

 

๋”ฐ๋ผ์„œ ๋ชจ๋“  ์ •์ ์„ ๋ฐฉ๋ฌธํ•˜๊ณ  ๋‚œ ํ›„ dist๋ฐฐ์—ด์€ ๋‹ค์Œ๊ณผ ๊ฐ™์Šต๋‹ˆ๋‹ค.

[ 0, 0, 1, 1, 2, 2, 2 ]

 

์ตœ๋Œ€ ๊ฑฐ๋ฆฌ๋Š” 2 ์ด๋ฏ€๋กœ filter์—ฐ์‚ฐ์„ ํ†ตํ•ด dist์—์„œ 2์˜ ๊ฐœ์ˆ˜๋ฅผ ๊ตฌํ•˜๋ฉด answer์€ 3์ด ๋ฉ๋‹ˆ๋‹ค.

 

[์ฝ”๋“œ]

function solution(n, edge) {
    var answer = 0;
    const graph = Array.from({length: n+1}, () => []);
    edge.forEach((item) => {
        graph[item[0]].push(item[1]);
        graph[item[1]].push(item[0]);
    });
    
    const findDist = () => {
        const dist = Array.from({length: n+1}, () => 0);
        const visit = Array.from({length: n+1}, () => false);
        let max = 0;
        const queue = [];
        visit[1] = true;
        queue.push(1);

        while(queue.length !== 0) {
            const q = queue.shift();
            for(let i=0;i<graph[q].length;i++) {
                const node = graph[q][i];
                if(visit[node]) {
                    continue;
                }
                dist[node] = dist[q] + 1;
                visit[node] = true;
                if(max < dist[node]) {
                    max = dist[node];
                }
                queue.push(node);
            }
        }
        answer = dist.filter((d) => d === max).length;
    }
    
    findDist();

    return answer;
}