문제
[프로그래머스] 단어 변환
풀이 과정
target 단어로 가는 최단 경로를 찾아야 하기 때문에 BFS로 구현.
target이 words에 없을 경우 0 반환.
begin을 큐에 삽입하고 words를 전부 순회하며 현재 큐에서 제거한 단어와 한 글자만 다른 단어를 큐에 삽입 후 방문처리.
이렇게 하면 words를 한 번 순회한 뒤에 큐에는 현재 원소와 한 글자만 다른 단어들이 들어가 있음.
만약 방문처리를 안해줄 경우 다시 바로 전에 방문했던 단어에 다싯 방문하기 때문에 무한루프에 빠짐.
코드
class Queue {
constructor() {
this.storage = {};
this.front = 0;
this.rear = 0;
}
size() {
if (this.storage[this.rear] === undefined) return 0;
return this.rear - this.front + 1;
}
enqueue(value) {
if (this.size() === 0) {
this.storage["0"] = value;
} else {
this.rear++;
this.storage[this.rear] = value;
}
}
dequeue() {
let temp = this.storage[this.front];
delete this.storage[this.front];
if (this.front === this.rear) {
this.front = 0;
this.rear = 0;
} else {
this.front++;
}
return temp;
}
}
function solution(begin, target, words) {
if (!words.some((e) => e === target)) return 0;
const n = words.length;
const wLen = begin.length;
let answer = 0;
const visited = Array.from({ length: n }, () => false);
const queue = new Queue();
queue.enqueue([begin, 0]);
while (queue.size()) {
let [cur, count] = queue.dequeue();
if (cur === target) break;
words.forEach((word, i) => {
if (!visited[i]) {
let splitCur = cur.split("");
let splitWord = word.split("");
let differ = 0;
for (let i = 0; i < wLen; i++) {
if (splitCur[i] !== splitWord[i]) differ++;
}
if (differ === 1) {
queue.enqueue([word, count + 1]);
visited[i] = true;
}
}
});
answer = count;
}
return answer+1;
}