프로그머스 - DFS/BFS - 단어 변환

Halo·2025년 7월 30일
0

Algorithm

목록 보기
77/85
post-thumbnail

🔍 Problem

프로그머스 - DFS/BFS - 단어 변환


📃 Input&Output


🌁 문제 배경

가. 문제 설명
두 개의 단어 begin, target과 단어의 집합 words가 있습니다. 아래와 같은 규칙을 이용하여 begin에서 target으로 변환하는 가장 짧은 변환 과정을 찾으려고 합니다.

  1. 한 번에 한 개의 알파벳만 바꿀 수 있습니다.
  2. words에 있는 단어로만 변환할 수 있습니다.
    예를 들어 begin이 "hit", target가 "cog", words가 ["hot","dot","dog","lot","log","cog"]라면 "hit" -> "hot" -> "dot" -> "dog" -> "cog"와 같이 4단계를 거쳐 변환할 수 있습니다.

두 개의 단어 begin, target과 단어의 집합 words가 매개변수로 주어질 때, 최소 몇 단계의 과정을 거쳐 begin을 target으로 변환할 수 있는지 return 하도록 solution 함수를 작성해주세요.

[제한사항]
각 단어는 알파벳 소문자로만 이루어져 있습니다.
각 단어의 길이는 3 이상 10 이하이며 모든 단어의 길이는 같습니다.
words에는 3개 이상 50개 이하의 단어가 있으며 중복되는 단어는 없습니다.
begin과 target은 같지 않습니다.
변환할 수 없는 경우에는 0를 return 합니다.

나. 접근 방법
BFS와 words의 인덱스 값을 사용하여 단어를 컨트롤 한다.

다. 문제 유형
BFS


📒 수도 코드

가. words안에 target이 있는지 check
없으면 0 return

나. BFS 큐에 첫번째 단계를 거처 변경될 수 있는 단어의 인덱스 넣기

다. BFS 구현

  1. 큐가 비지 않으면 반복

  2. 큐에서 하나 뽑기

  3. 다음단계로 갈 수 있을 때(알파벳이 하나만 다른 값 for문으로 탐색)

    a. 만약 탐색한 인덱스가 i이면, dist[i]가 0이고 다음단계로 갈 수 있는 i이면
    -> dist[i]+1=dist[큐에서 하나뽑은 인덱스]
    -> 만약 이 값이 타겟값과 같다면 return dist[i]


💻 Code

import java.util.*;

class Solution {
    
    boolean canChange(String w1, String w2){
        int cnt=0;

        for(int i=0; i<w1.length(); i++){
            if(w1.charAt(i) != w2.charAt(i)){
                cnt++;
            }
            if(cnt==2){
                return false;
            }
        }
        return true;
        
    }
    
    public int solution(String begin, String target, String[] words) {
        
        int answer = 0;
        
        if(!Arrays.asList(words).contains(target)){
            return 0;
        }
        
        Queue<Integer> que = new LinkedList<>();
        int[] dist = new int[words.length];
        
        
        // 큐에 미리 하나 넣어놓기 첫번째 후보군들
        for(int i=0; i<words.length; i++){
            if(canChange(words[i],begin)){
                dist[i]=1;
                que.add(i);
            }
        }
        
        
        while(!que.isEmpty()){
            int word_idx = que.poll();
            
            for(int i=0; i<words.length; i++){
                if(dist[i] == 0 && canChange(words[i],words[word_idx])){
                    que.add(i);
                    dist[i]=dist[word_idx]+1;
                    if(words[i].equals(target)){
                        return dist[i];
                    }
                }
            }
        }
        
        return dist[Arrays.asList(words).indexOf(target)];
    }
}


🎸 기타

가. Arrays.asList(arr).contains(value)

  • return : arr에서 value를 포함하는지

니. Arrays.asList(arr).indexOf(value)

  • return : arr에서 value의 인덱스

🤓 성능


🤔 느낀점

BFS 큐의 자료형을 words의 인덱스인 Integer로 할 생각을 처음에 하지 못해서 해맸던 문제이다.

profile
새끼 고양이 키우고 싶다

0개의 댓글