[JavaScript] 프로그래머스 단어변환 LEVEL2

김예진·2021년 1월 11일
1

코딩 테스트

목록 보기
4/42
let answer = 100;
let visit;

const bfs = (begin, target, words, cnt) => {
    if (begin === target) {
      if (answer > cnt) answer = cnt;
      return;
    }
    
    for (let i=0; i<words.length; i++) {
        let notsame = 0;
        if (visit[i]) continue;
            
        for (let j=0; j<begin.length; j++) {
            if (begin[j] !== words[i][j]) notsame++;
        }

        if (notsame === 1) {
            visit[i] = true;
            bfs(words[i], target, words, cnt + 1);
            visit[i] = false;
        }
    }
};

function solution(begin, target, words) {
    visit = Array.from(words.length).fill(false);
    
    if (!words.includes(target)) return 0;
    
    bfs(begin, target, words, 0);
    
    return answer === 100 ? 0 : answer;
}

0개의 댓글