[프로그래머스] 단어 변환 (Javascript)

잭슨·2024년 2월 10일
0

알고리즘 문제 풀이

목록 보기
122/130
post-thumbnail

문제

[프로그래머스] 단어 변환

풀이 과정

  1. target 단어로 가는 최단 경로를 찾아야 하기 때문에 BFS로 구현.
  2. targetwords에 없을 경우 0 반환.
  3. 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) {
    // words에 target이 없을 경우 0 반환
    if (!words.some((e) => e === target)) return 0; 

    const n = words.length; // words의 길이
    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();
        // 현재 단어가 target과 일치하다면 반복문 중단
        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]); // count+1 대신 count++로 할 경우 증가 안됨
                    visited[i] = true;
                }
            }
        });
        answer = count;
    }
    return answer+1;
}
profile
지속적인 성장

0개의 댓글