코딩테스트

[다시풀기/단어변환]

_서리__ 2023. 6. 5. 22:16
function solution(begin, target, words) {
    let obj = {};
    words.push(begin)
    //words에서 한단어만 다른 것을 찾음. 이걸 DFS든 BFS든 반복하다가 (DFS가 맞을듯) target이 나오면 멈춤.
    //최소 -> 최단거리 BFS..???
    for(let i=0;i<words.length;i++){
        obj[words[i]]=[];
        for(let j=0;j<words.length;j++){
            for(let k=0;k<words[i].length;k++){
                let newWords1 = words[i].slice(0,k)+words[i].slice(k+1)
                let newWords2 = words[j].slice(0,k)+words[j].slice(k+1)
                if(i!==j&&newWords1===newWords2){
                    obj[words[i]].push(words[j])
                }
            }
        }
    }

    function bfs(){
    const visited = {}
    const queue = [[begin,0]]
    while(queue.length){
        const [node,count] = queue.shift();
        if(node===target) return count;
        visited[node] = true;
        obj[node].forEach((el)=>{
            if(!visited[el]){
                queue.push([el,count+1])
            }
        })
    }
    }
    let answer = bfs()
    return answer?answer:0;
}

무려 포문을 세개를 써서 연결그래프 obj를 만들었다. 그 이후 bfs를 이용해 최단거리를 구해줬는데 최단거리 구하는것에 있어서 정말 많이 애를 먹었다..ㅠㅠ