개발아 담하자

[프로그래머스/C++] 단어 변환 풀이 본문

👩‍💻 알고리즘 풀이/프로그래머스

[프로그래머스/C++] 단어 변환 풀이

choidam 2020. 9. 30. 22:31

프로그래머스 : 단어 변환 풀이

문제 링크 : programmers.co.kr/learn/courses/30/43163


문제

두 개의 단어 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 함수를 작성해주세요.


간단한 탐색 문제이다. isChangable 을 사용해 탐색 가능한 지 여부를 확인하고 DFS 탐색을 진행했다.

ans 의 초기값이 100인 이유는 words의 최대 size가 50이므로 51이상 될 수 없기 때문이다.

 

문제 풀이

#include <string>
#include <vector>

using namespace std;
int answer = 100;

bool isChangable(string str1, string str2){
    int diff = 0;
    for(int i=0; i<str1.length(); i++){
        if(str1[i] != str2[i]){
            diff++;
        }
    }
    if(diff==1) return true;
    else return false;
}

void dfs(string begin, string target, vector<string> words, vector<bool> &visited, int time){
    for(int i=0; i<words.size(); i++){
        if(isChangable(begin, words[i])){ // 변환 가능
            // 최종 도착 여부 검사 -> 종료
            if(target==words[i]){
                if(time+1 < answer) {
                    answer = time+1;
                    return;
                }
            }
            
            // 방문 여부 검사 -> 다시 탐색
            if(visited[i]==false){
                visited[i] = true;
                dfs(words[i], target, words, visited, time+1);
            }
        }
   } 
}

int solution(string begin, string target, vector<string> words) {
    vector<bool> visited(words.size(), false);
    
    dfs(begin, target, words, visited, 0);
    
    if(answer==100) return 0;
    else return answer;
}

 

단어 변환 풀이 인증