- Published on
프로그래머스 단어변환 (bfs/dfs)
- Authors
- Name
- Deokgoo Kim
문제 풀이
bfs/dfs 분류의 문제입니다. bfs로 풀었습니다.
난이도는 중간이라고 생각합니다.
function solution(begin, target, words) {
let visited = new Array(words.length).fill(-1);
let targetIndex = words.indexOf(target);
let queue = [];
if(targetIndex === -1) return 0;
function bfs(queue) {
while(queue.length) {
const { word, level } = queue.shift();
for(let i=0;i<words.length;i++) {
let diff = 0;
if(visited[i] !== -1 && visited[i]<=level) continue;
for(let j = 0;j<word.length;j++) {
if(words[i][j] !== word[j]) diff++;
if(diff > 1) break;
}
if(diff === 1) {
visited[i] = level + 1;
if(words[i] === target) return;
queue.push({word: words[i], level: level + 1});
}
}
}
}
queue.push({word: begin, level: 0});
bfs(queue);
return visited[targetIndex]
}