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;
}