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

Daehyunii's Dev-blog

์ค‘๋ณต์ˆœ์—ด ๊ตฌํ•˜๊ธฐ(DFS) ๋ณธ๋ฌธ

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

์ค‘๋ณต์ˆœ์—ด ๊ตฌํ•˜๊ธฐ(DFS)

Daehyunii 2022. 9. 7. 21:56

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

 

1๋ถ€ํ„ฐ N๊นŒ์ง€ ๋ฒˆํ˜ธ๊ฐ€ ์ ํžŒ ๊ตฌ์Šฌ์ด ์žˆ์Šต๋‹ˆ๋‹ค. ์ด ์ค‘ ์ค‘๋ณต์„ ํ—ˆ๋ฝํ•˜์—ฌ M๋ฒˆ์„ ๋ฝ‘์•„ ์ผ๋ ฌ๋กœ ๋‚˜์—ด ํ•˜๋Š” ๋ฐฉ๋ฒ•์„ ๋ชจ๋‘ ์ถœ๋ ฅํ•ฉ๋‹ˆ๋‹ค.

 

โ–ฃ ์ž…๋ ฅ์„ค๋ช…
์ฒซ ๋ฒˆ์งธ ์ค„์— ์ž์—ฐ์ˆ˜ N(3<=N<=10)๊ณผ M(2<=M<=N) ์ด ์ฃผ์–ด์ง‘๋‹ˆ๋‹ค.

 

โ–ฃ ์ถœ๋ ฅ์„ค๋ช…
์ฒซ ๋ฒˆ์งธ ์ค„์— ๊ฒฐ๊ณผ๋ฅผ ์ถœ๋ ฅํ•ฉ๋‹ˆ๋‹ค. ๋งจ ๋งˆ์ง€๋ง‰ ์ด ๊ฒฝ์šฐ์˜ ์ˆ˜๋ฅผ ์ถœ๋ ฅํ•ฉ๋‹ˆ๋‹ค. ์ถœ๋ ฅ์ˆœ์„œ๋Š” ์‚ฌ์ „์ˆœ์œผ๋กœ ์˜ค๋ฆ„์ฐจ์ˆœ์œผ๋กœ ์ถœ๋ ฅํ•ฉ๋‹ˆ๋‹ค.

 

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

32

 

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

11
12
13

21 22 23 31 32 33 9

 

Tip

 

๋ฌธ์ œํ’€์ด

//์ •๋‹ต
function solution(n, m){
    let answer=[];
    let tmp=Array.from({length:m}, ()=>0);
    function DFS(L){
        if(L===m){
            answer.push(tmp.slice());
        }
        else{
            for(let i=1; i<=n; i++){ // ์„ธ ๊ฐ€์ง€๋กœ ๋ป—์–ด ๋‚˜๊ฐ
                tmp[L]=i;
                DFS(L+1);
            }
        }   
    }

    DFS(0);
    return answer;
}

console.log(solution(3, 2));