단어 변환
function shouldConvert(standard, target, option) {
let count = 0;
for (let i = 0; i < standard.length; i++) {
count += standard[i] == target[i] ? 1 : 0;
}
if (count == option - 1) {
return true;
}
return false;
}
function solution(begin, target, words) {
if (!words.includes(target)) {
return 0;
}
let minRoute = Infinity;
function dfs(node, count, visited) {
if (node == target) {
if (count < minRoute) {
minRoute = count;
}
return;
}
visited[node] = true;
const length = node.length;
const neighbors = words.filter(
(word) =>
shouldConvert(node, word, length) && !visited.hasOwnProperty(word)
);
if (!neighbors.length) {
return;
}
for (const neighbor of neighbors) {
dfs(neighbor, count + 1, { ...visited });
}
}
dfs(begin, 0, {}, []);
if (minRoute == Infinity) {
return 0;
}
return minRoute;
}