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

문제 설명

두 개의 단어 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 합니다.
#include <string>
#include <vector>
#include <bits/stdc++.h>

using namespace std;

#define X first 
#define Y second 



//몇글자가 같은지 return 
int compare_str(string a, string b){
    int ans=0;
    for(int i=0;i<a.size();i++){
        if(a[i]==b[i]) ans++;
    }
    return ans;
}

int bfs(string begin, string target, vector<string> words, queue<pair<int,string>> q, int next[]){
    int ans=1;
    while(!q.empty()){
        pair<int,string> cur=q.front(); q.pop();
        if(cur.Y==target) return next[cur.X];
        for(int i=0;i<words.size();i++){
            if(compare_str(cur.Y,words[i])==words[i].size()-1&&next[i]==0){
                q.push({i,words[i]});
                next[i]=next[cur.X]+1;
            }
        }
    }
    return 0;
}

int solution(string begin, string target, vector<string> words) {
    int answer = 51;
    int next[51]={0,};
    //bfs로 next가 있는지 점검.. 
    //1텀이 될 수 있는 걸 먼저 찾고 
    //q에 넣어서 for문으로 탐색 
    queue<pair<int,string>> q;
    for(int i=0;i<words.size();i++){
        if(compare_str(begin,words[i])==words[i].size()-1){
            next[i]=1;
            q.push({i,words[i]}); 
        }
    }
    int tmp=bfs(begin,target,words,q,next);
    if(tmp<answer) answer=tmp;
    return answer;
}