단어 변환

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, {}, []);

  // words에는 target이 있지만, 경로상 도달할 수 없는 경우
  if (minRoute == Infinity) {
    return 0;
  }
  return minRoute;
}
  • 문제를 잘 읽자 ㅠㅠ

0개의 댓글