[Level3] 단어 변환




단어 변환

프로그래머스

나의 풀이 (bfs)

function solution(begin, target, words) {
  var answer = 0;
  if (!words.includes(target)) return 0;

  const queue = [begin];
  const visited = new Set();
  let temp = [];

  const oneDiff = (target, compare) => {
    let cnt = 0;
    for (let i = 0; i < target.length; i++) {
      if (target[i] !== compare[i]) cnt++;
    }
    return cnt === 1 ? true : false;
  };

  while (queue.length) {
    const cur = queue.shift();
    visited.add(cur);

    if (cur === target) return answer;

    for (let i = 0; i < words.length; i++) {
      if (!visited.has(words[i]) && oneDiff(cur, words[i])) temp.push(words[i]);
    }

    if (!queue.length) {
      answer++;
      queue.push(...temp);
      temp = [];
    }
  }
  return answer;
}

// console.log(oneDiff('abc', 'abb'));
console.log(solution('hit', 'cog', ['hot', 'dot', 'dog', 'lot', 'log']));

문제 유형 상, dfs로 푸는 것보다 bfs로 푸는 것이 효율적이지만 공부를 위해 dfs로 풀어보자



나의 풀이 (dfs)

function solution(begin, target, words) {
  const answer = [];
  if (!words.includes(target)) return 0;

  const visited = new Set();

  const oneDiff = (target, compare) => {
    let cnt = 0;
    for (let i = 0; i < target.length; i++) {
      if (target[i] !== compare[i]) cnt++;
    }
    return cnt === 1 ? true : false;
  };

  const dfs = (cur, words, visited, level) => {
    if (cur === target) {
      answer.push(level);
      return;
    }

    for (let i = 0; i < words.length; i++) {
      if (!visited.has(words[i]) && oneDiff(cur, words[i])) {
        visited.add(cur);
        dfs(words[i], words, visited, level + 1);
        visited.delete(cur);
      }
    }

    return;
  };

  dfs(begin, words, visited, 0);
  return Math.min(...answer);
}

// console.log(oneDiff('abc', 'abb'));
console.log(solution('hit', 'cog', ['hot', 'dot', 'dog', 'lot', 'log', 'cog']));
// console.log(solution('hit', 'cog', ['hot', 'dot', 'dog', 'lot', 'log']));