๐Ÿ“’ Algorithm

[์ฝ”๋”ฉ ํ…Œ์ŠคํŠธ ํ•ฉ๊ฒฉ์ž ๋˜๊ธฐ ๋ฌธ์ œ 39] ๋„ˆ๋น„ ์šฐ์„  ํƒ์ƒ‰ ์ˆœํšŒ

s2ylvia 2024. 9. 26. 00:36

๋ฌธ์ œ ์„ค๋ช…

๋„ˆ๋น„ ์šฐ์„  ํƒ์ƒ‰์œผ๋กœ ๋ชจ๋“  ๊ทธ๋ž˜ํ”„์˜ ๋…ธ๋“œ๋ฅผ ์ˆœํšŒํ•˜๋Š” ํ•จ์ˆ˜ solution()์„ ์ž‘์„ฑํ•˜์„ธ์š”. ์‹œ์ž‘ ๋…ธ๋“œ๋Š” start๋กœ ์ฃผ์–ด์ง‘๋‹ˆ๋‹ค. graph๋Š” [์ถœ๋ฐœ ๋…ธ๋“œ, ๋„์ฐฉ ๋…ธ๋“œ] ์Œ๋“ค์ด ๋“ค์–ด ์žˆ๋Š” ๋ฐฐ์—ด์ž…๋‹ˆ๋‹ค. ๋ฐ˜ํ™˜๊ฐ’์€ ๊ทธ๋ž˜ํ”„์˜ ์‹œ์ž‘ ๋…ธ๋“œ๋ถ€ํ„ฐ ๋ชจ๋“  ๋…ธ๋“œ๋ฅผ ๋„ˆ๋น„ ์šฐ์„  ํƒ์ƒ‰์œผ๋กœ ์ง„ํ–‰ํ•œ ์ˆœ์„œ๋Œ€๋กœ ๋…ธ๋“œ๊ฐ€ ์ €์žฅ๋œ ๋ฐฐ์—ด์ž…๋‹ˆ๋‹ค.

 

์ œ์•ฝ ์กฐ๊ฑด

  • ๋…ธ๋“œ์˜ ์ตœ๋Œ€ ๊ฐœ์ˆ˜๋Š” 100๊ฐœ๋ฅผ ๋„˜์ง€ ์•Š์Šต๋‹ˆ๋‹ค.
  • ์‹œ์ž‘ ๋…ธ๋“œ๋ถ€ํ„ฐ ์‹œ์ž‘ํ•ด์„œ ๋ชจ๋“  ๋…ธ๋“œ๋ฅผ ๋ฐฉ๋ฌธํ•  ์ˆ˜ ์žˆ๋Š” ๊ฒฝ๋กœ๊ฐ€ ํ•ญ์ƒ ์žˆ์Šต๋‹ˆ๋‹ค.
  • ๊ทธ๋ž˜ํ”„์˜ ๋…ธ๋“œ๋Š” ์ˆซ์ž์ž…๋‹ˆ๋‹ค.

์ž…์ถœ๋ ฅ์˜ ์˜ˆ

graph start return
[(1,2),(1,3),(2,4),(2,5),(3,6),(3,7),(4,8),(5,8),(6,9),(7,9)] 1 [1,2,3,4,5,6,7,8,9]
[(0,1),(1,2),(2,3),(3,4),(4,5),(5,0)] 1 [1,2,3,4,5,0]

 

์ •๋‹ต

function solution(graph, start) {
    //๊ทธ๋ž˜ํ”„๋ฅผ ์ธ์ ‘ ๋ฆฌ์ŠคํŠธ๋กœ
    const adjList = {};
    
    for(const [start,end] of graph){
        if(!adjList[start]) adjList[start] = [];
        adjList[start].push(end);
    }
    
    const visited = new Set(); //๋ฐฉ๋ฌธ ์—ฌ๋ถ€ ์ฒ˜๋ฆฌ
    const queue = []; //ํ๋กœ bfs๋ฅผ ๋Œ๋ฆด๊ฑฐ์ž„
    
    queue.push(start);
    visited.add(start); //์‹œ์ž‘ ๋…ธ๋“œ๋ฅผ ๋ฐ”๋กœ ๋ฐฉ๋ฌธ์ฒ˜๋ฆฌ
    const result = [start]; //๋ฐ”๋กœ ์‹œ์ž‘๋…ธ๋“œ ๊ฒฐ๊ณผ๋ฐฐ์—ด์— ํ‘ธ์‰ฌ
    
    //ํ ๋นŒ๋•Œ๊นŒ์ง€ ๋Œ๋ฆฐ๋‹ค
    while(queue.length > 0){
        const node = queue.shift(); //ํŒํ•ด์„œ ์ธ๊ทผ ๋…ธ๋“œ๋ฅผ ์ฐพ์„๊ฑฐ์ž„
        for(let neighbor of adjList[node] || []){
            if(!visited.has(neighbor)){
                //๋ฐฉ๋ฌธํ•˜์ง€์•Š์•˜์„ ๊ฒฝ์šฐ ํƒ์ƒ‰
                queue.push(neighbor);
                visited.add(neighbor);
                result.push(neighbor);
            }
        }
    }
    
    return result;
}