본문 바로가기

Algorithm

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

문제 설명

두 개의 단어 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 합니다.

입출력 예

begin target words return
"hit" "cog" ["hot", "dot", "dog", "lot", "log", "cog"] 4
"hit" "cog" ["hot", "dot", "dog", "lot", "log"] 0

입출력 예 설명

예제 #1
문제에 나온 예와 같습니다.

예제 #2
target인 "cog"는 words 안에 없기 때문에 변환할 수 없습니다.

https://programmers.co.kr/learn/courses/30/lessons/43163

 

코딩테스트 연습 - 단어 변환

두 개의 단어 begin, target과 단어의 집합 words가 있습니다. 아래와 같은 규칙을 이용하여 begin에서 target으로 변환하는 가장 짧은 변환 과정을 찾으려고 합니다. 1. 한 번에 한 개의 알파벳만 바꿀 수

programmers.co.kr


내 소스

 

class Solution {
    String target;
    String[] words;
    int len;
    boolean[] left;
    int answer;
    
    //한글자만 다른지 체크하는 함수
    public boolean convertable(String a, String b){
        int count = 0;
        for(int i=0; i<a.length(); i++){
            if(a.charAt(i) != b.charAt(i)){
                count++;
            }
        }
        if(count == 1){
            return true;
        }else{
            return false;
        }
    }

    public int solution(String begin, String target, String[] words) {
        int i;
        int target_idx = -1;
        len = words.length+1;
        left = new boolean[len];
        String[] new_words = new String[len];

        this.words = new_words;
        this.target = target;
        answer = 100; //max value로 초기화

        //new_words : words 배열에 begin이 추가됨
        //words 안에 target이 없으면 0 출력
        for(i=0; i<len-1; i++){
            new_words[i] = words[i];
            if(words[i].equals(target)){
                target_idx = i;
            }
        }
        if(target_idx == -1){
            return 0;
        }
        new_words[len-1] = begin;

        //left : 남은 단어들이 뭐가 있는지 체크하는 배열
        //begin 위치 빼고 true로 초기화 (begin : 시작점)
        for(i=0; i<len; i++){
            left[i] = true;
        }
        left[len-1] = false;

        //begin부터 깊이우선탐색 시작
        dfs(len-1, 0);

        if(answer == 100){
            answer = 0;
        }

        return answer;
    }

    public void dfs(int idx, int depth){
        //target 찾음
        if(words[idx].equals(target)){
            //지금까지 찾은 경로보다 더 최적화된 depth일 경우
            if(depth < answer){
                answer = depth;
            }
        }
        //지금까지 찾은 경로보다 depth가 더 깊은 경우
        //(최단 depth를 구하는 것이므로 더 찾을 필요 없음)
        else if(answer <= depth){
            return;
        }
        else{
            for(int i=0; i<len; i++){
                if(idx == i || !left[i]){ continue; }
                if(convertable(words[idx], words[i])){
                    left[i] = false;
                    dfs(i, depth+1);
                    left[i] = true;
                }
            }
        }
    }
}