๊ด€๋ฆฌ ๋ฉ”๋‰ด

Daehyunii's Dev-blog

์ธ์ ‘ ๋ฆฌ์ŠคํŠธ ๊ฒฝ๋กœ ํƒ์ƒ‰(DFS) ๋ณธ๋ฌธ

๐Ÿ“š Language & CS knowledge/Algorithm (๊ธฐ์ดˆ๋ฌธ์ œํ’€์ด)

์ธ์ ‘ ๋ฆฌ์ŠคํŠธ ๊ฒฝ๋กœ ํƒ์ƒ‰(DFS)

Daehyunii 2022. 9. 7. 22:19

๋ฌธ์ œ(์ถœ์ฒ˜ : ์ธํ”„๋Ÿฐ ์ž๋ฐ”์Šคํฌ๋ฆฝํŠธ ์•Œ๊ณ ๋ฆฌ์ฆ˜ ๋ฌธ์ œํ’€์ด ๊ฐ•์˜, ์ •๋ณด์˜ฌ๋ฆผํ”ผ์•„๋“œ)

 

๋ฐฉํ–ฅ๊ทธ๋ž˜ํ”„๊ฐ€ ์ฃผ์–ด์ง€๋ฉด 1๋ฒˆ ์ •์ ์—์„œ N๋ฒˆ ์ •์ ์œผ๋กœ ๊ฐ€๋Š” ๋ชจ๋“  ๊ฒฝ๋กœ์˜ ๊ฐ€์ง€ ์ˆ˜๋ฅผ ์ถœ๋ ฅํ•˜๋Š” ํ”„ ๋กœ๊ทธ๋žจ์„ ์ž‘์„ฑํ•˜์„ธ์š”. ์•„๋ž˜ ๊ทธ๋ž˜ํ”„์—์„œ 1๋ฒˆ ์ •์ ์—์„œ 5๋ฒˆ ์ •์ ์œผ๋กœ ๊ฐ€๋Š” ๊ฐ€์ง€ ์ˆ˜๋Š”

12345

125 
13425
1345

1425

145

์ด 6 ๊ฐ€์ง€์ž…๋‹ˆ๋‹ค.

โ–ฃ ์ž…๋ ฅ์„ค๋ช…
์ฒซ์งธ ์ค„์—๋Š” ์ •์ ์˜ ์ˆ˜ N(1<=N<=20)์™€ ๊ฐ„์„ ์˜ ์ˆ˜ M๊ฐ€ ์ฃผ์–ด์ง„๋‹ค. ๊ทธ ๋‹ค์Œ๋ถ€ํ„ฐ M์ค„์— ๊ฑธ์ณ ์—ฐ ๊ฒฐ์ •๋ณด๊ฐ€ ์ฃผ์–ด์ง„๋‹ค.

โ–ฃ ์ถœ๋ ฅ์„ค๋ช…
์ด ๊ฐ€์ง€์ˆ˜๋ฅผ ์ถœ๋ ฅํ•œ๋‹ค.

 

โ–ฃ ์ž…๋ ฅ์˜ˆ์ œ 1

5 9

1 2

1 3

1 4

2 1  

2 3

2 5

3 4

4 2

4 5

 

โ–ฃ ์ถœ๋ ฅ์˜ˆ์ œ 1

6

 

Tip

 

๋ฌธ์ œํ’€์ด

//์ •๋‹ต๋ณด๊ณ  ๋‚ด๊ฐ€ ๋‹ค์‹œ ์ž‘์„ฑํ•œ ์ •๋‹ต
function solution(n, arr){
    let answer = 0;
    let graph = Array.from(Array(n+1),()=>Array());
    let check = Array.from({length : n+1},()=>0);

    for(let [a,b] of arr){
        graph[a].push(b);
    }

    function DFS(vertex){
        if(vertex === 5){
            answer++;
        }
        else{
            for(let newVertex of graph[vertex]){
                if(check[newVertex] === 0){
                    check[newVertex] = 1;
                    DFS(newVertex);
                    check[newVertex] = 0;
                }
            }
        }
    }
    check[1] = 1;
    DFS(1)
    return answer;
}


let arr2=[[1, 2], [1, 3], [1, 4], [2, 1], [2, 3], [2, 5], [3, 4], [4, 2], [4, 5]];
console.log(solution(5, arr2));