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

2 minute read

문제 설명

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

풀이

30분
방문한 word를 체크하기 위한 visit 배열을 선언한 뒤, dfs를 적용하였다. 코드가 길어진 이유는 solution 함수에서 begin 문자열에서 한 개의 알파벳만 바꿔 만들 수 있는 문자열을 찾아서 코드가 중복되었다. dfs함수의 인자로 string을 사용했다면 solution 함수의 반복문을 없앨 수 있을텐데, 동작은 똑같으니 일단 제출한 뒤 코드를 다시 고쳤다.

코드

// 07:46 ~ 08:11
#include <string>
#include <vector>

using namespace std;

int res = 51;
int visit[50] = {0};
string target;
vector<string> words;

void dfs(int cnt, int idx){
    string word = words[idx];
    visit[idx] = 1;
    ++cnt;
    
    if(word == target){
        if(cnt < res) res = cnt;
        visit[idx] = 0;
        return;
    }
    
    int dup_cnt = 0;
    
    for(int i = 0; i < words.size(); ++i){
        dup_cnt = 0;
        if(visit[i] == 1) continue;
        for(int j = 0; j < target.length(); ++j){
            if(word[j] != words[i][j]){
                ++dup_cnt;
                if(dup_cnt > 1) break;
            }
        }
        if(dup_cnt <= 1) dfs(cnt,i);
    }
    
    visit[idx] = 0;
}

int solution(string begin, string _target, vector<string> _words) {
    target = _target;
    words = _words;
    int cnt;
    for(int i = 0; i < words.size(); ++i){
        cnt = 0;
        for(int j = 0; j < begin.length(); ++j){
            if(begin[j] != words[i][j]){
                ++cnt;
                if(cnt > 1) break;
            }
        }
        if(cnt <= 1) dfs(0,i);
    }
    
    if(res == 51) return 0;
    return res;
}

고친 코드

#include <string>
#include <vector>

using namespace std;

int res = 51;
int visit[50] = {0};
string target;
vector<string> words;

void dfs(int cnt, string begin){
    if(begin == target){
        if(cnt < res) res = cnt;
        return;
    }
    
    int dup_cnt = 0;
    
    for(int i = 0; i < words.size(); ++i){
        dup_cnt = 0;
        if(visit[i] == 1) continue;
        for(int j = 0; j < begin.length(); ++j){
            if(begin[j] != words[i][j]){
                ++dup_cnt;
                if(dup_cnt > 1) break;
            }
        }
        if(dup_cnt <= 1){
            visit[i] = 1;
            dfs(cnt + 1,words[i]);
            visit[i] = 0;
        }
    }
}

int solution(string begin, string _target, vector<string> _words) {
    target = _target;
    words = _words;
    
    dfs(0, begin);
   
    if(res == 51) return 0;
    return res;
}