๋ณธ๋ฌธ ๋ฐ”๋กœ๊ฐ€๊ธฐ
๐Ÿง  ์•Œ๊ณ ๋ฆฌ์ฆ˜

[ํ”„๋กœ๊ทธ๋ž˜๋จธ์Šค] ์—ฌํ–‰๊ฒฝ๋กœ JS

by megan07 2023. 12. 27.

์ ‘๊ทผ๋ฐฉ๋ฒ•๐Ÿ’ก

๋ชจ๋“  ํ‹ฐ์ผ“๋“ค์˜ ์ถœ๋ฐœ์ง€๋ฅผ ํ‚ค๊ฐ’์œผ๋กœ ํ•˜๋Š” ์ธ์ ‘๋ฆฌ์ŠคํŠธ๋ฅผ ๋งŒ๋“ค๊ธฐ
์•ŒํŒŒ๋ฒณ ์ˆœ์œผ๋กœ ์ •๋ ฌ
dfs๋กœ ํƒ์ƒ‰
ํƒˆ์ถœ ์กฐ๊ฑด์€ ๊ฒฝ๋กœ์˜ ๊ธธ์ด๊ฐ€ tickets์˜ length์™€ ๊ฐ™์„ ๋•Œ

function solution(tickets) {
   
    const adjacencyList = {};
    
    let result=[];
    
    //์ธ์ ‘๋ฆฌ์ŠคํŠธ [key=์ถœ๋ฐœ์ง€]:๋„์ฐฉ์ง€[] 
    tickets.forEach(t=>{
        const [dep, arr]=t;
        const tmp=adjacencyList[dep]||[];
        tmp.push(arr);        
        adjacencyList[dep]=tmp;
    });
    
    //์•ŒํŒŒ๋ฒณ ์ˆœ์œผ๋กœ ์ •๋ ฌ
    for(key in adjacencyList){
        adjacencyList[key].sort();
    }
    

    
    //์žฌ๊ท€ํ•จ์ˆ˜ dfs
    //path=์ง€๊ธˆ๊นŒ์ง€์˜ ๊ฒฝ๋กœ, dep=์ถœ๋ฐœ์ง€
    //๋ฐฑํŠธ๋ž˜ํ‚น์„ ํ•ด์•ผ ํ•˜๊ธฐ ๋•Œ๋ฌธ์— ์ธ์ˆ˜๋กœ ์ง€๊ธˆ๊นŒ์ง€ ๊ฒฝ๋กœ๋ฅผ ๋‹ด์€ ๋ฐฐ์—ด์„ ์ „๋‹ฌํ•ด์คŒ
    function dfs(path, dep){
    
    //ํƒˆ์ถœ ์กฐ๊ฑด = ๊ฒฝ๋กœ์˜ ๊ธธ์ด๊ฐ€ total๊ฐ€ ๊ฐ™์„ ๋•Œ
        if(path.length===tickets.length){
        	//result ๋ฐฐ์—ด์— ๋งˆ์ง€๋ง‰์œผ๋กœ ๋ฐ›์€ dep๊ฐ’ ๋„ฃ์–ด์ฃผ๊ธฐ
            result = [...path, dep];
            return true;
        }
        
        const temp=adjacencyList[dep]?[...adjacencyList[dep]]:[];

        temp?.forEach(city=>{
        	//๋ฆฌ์ŠคํŠธ๋ฅผ ํ๋ผ๊ณ  ์ƒ๊ฐํ•˜๊ณ  ๋งจ ์•ž์˜ ๋„์‹œ๋ฅผ popํ•˜๊ณ 
            //๋‹ค์‹œ dfs๋กœ ํƒ์ƒ‰
            adjacencyList[dep].shift();
            if(dfs([...path, dep], city)){
                return true;
            };
           //์กฐ๊ฑด์— ๋งž๋Š” ๊ฒฝ๋กœ๋ฅผ ์ฐพ๊ธฐ ๋ชปํ–ˆ์„ ๊ฒฝ์šฐ
           //์ œ๊ฑฐํ–ˆ๋˜ ๋„์‹œ๋ฅผ ๋’ค์— ๋‹ค์‹œ ๋„ฃ์–ด์คŒ
            adjacencyList[dep].push(city);
        })
        
        return false;
        
        
    }
    dfs([],"ICN");
    
  return result;
    
    


}

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