문제

풀이
은찬
const countDiffer = (word, target) => { let count = 0; for(let i = 0; i < word.length; i++){ if(word[i] !== target[i]){ count++; } } return count === 1 ? true : false; } const solution = (begin, target, words) => { let answer = 0; const queue = []; const map = new Map(); queue.push(begin); while(queue.length){ let size = queue.length; while(size--){ const currentWord = queue.shift(); if(currentWord === target){ return answer; } for(let i = 0; i < words.length; i++){ const word = words[i]; if(currentWord === word){ continue; } if(!map.get(currentWord + word) && !map.get(word + currentWord) && countDiffer(currentWord, word)){ queue.push(word); map.set(currentWord + word, true); map.set(word + currentWord, true); } } } answer++; } return 0; }
재영
const solution = (begin, target, words) => { const q = []; const wordLength = begin.length; q.push([begin, words, 0]) // 바뀐 횟수 while (q.length) { const [now, words, cnt] = q.shift(); if (now === target) { return cnt; } for (let i = 0; i < words.length; i += 1) { const word = words[i]; let diffCount = 0; for (let j = 0; j < wordLength; j += 1) { diffCount += word[j] !== now[j]; } if (diffCount === 1) { q.push([word, words.filter(w => w !== word), cnt + 1]) } } } return 0; // 바뀔 수 없음. }
효성
내 풀이 - 실패
원인 : queue 개념을 생각 못했다...
function solution(begin, target, words) { let answer = 0; if(checkWords(begin, words)) { answer++; let changed = checkWords() } } function checkWords(word, wordArr) { for(let i=0; i<wordArr.length; i++) { if(canChange(word, wordArr[i])) { return wordArr[i]; } } } function canChange(original, compare) { let leftCnt = 1; for(let j=0; j<original.length; j++) { if(original[j] !== compare[j]) { if(leftCnt) { leftCnt--; } else { return false; } } } return true; }
참고한 풀이
function solution(begin, target, words) { let visited = [], queue = []; if(!words.includes(target)) return 0; queue.push([begin, 0]); while(queue) { let [char, cnt] = queue.shift(); if(char === target) { return cnt; } words.forEach(word => { let notSame = 0; if(visited.includes(word)) return; for(let i=0; i<word.length; i++) { if(word[i] !== char[i]) notSame++; } if(notSame === 1) { queue.push([word, ++cnt]); visited.push(word); } }); } return 0; }