두 개의 단어 begin, target과 단어의 집합 words가 있습니다. 아래와 같은 규칙을 이용하여 begin에서 target으로 변환하는 가장 짧은 변환 과정을 찾으려고 합니다.
두 개의 단어 begin, target과 단어의 집합 words가 매개변수로 주어질 때, 최소 몇 단계의 과정을 거쳐 begin을 target으로 변환할 수 있는지 return 하도록 solution 함수를 작성해주세요.
각 단어는 알파벳 소문자로만 이루어져 있습니다.
각 단어의 길이는 3 이상 10 이하이며 모든 단어의 길이는 같습니다.
words에는 3개 이상 50개 이하의 단어가 있으며 중복되는 단어는 없습니다.
begin과 target은 같지 않습니다.
변환할 수 없는 경우에는 0를 return 합니다.
CalcDiff 함수를 구현하여 단어별 차이글자 수를 반환하게 하고 이를 바탕으로 CalcDiff가 1이고 vistied 하지 않은 경우에만 탐색하게 하여 BFS를 구현하였다.
#include <string>
#include <vector>
#include <queue>
#include <algorithm>
#include <iostream>
using namespace std;
vector<bool> visited(50);
queue<pair<string,int>> q;
int CalcDiff(const string& lhs,const string& rhs){
int miss = 0;
for(int i=0;i<lhs.size();i++){
if(lhs[i] != rhs[i])
miss++;
}
return miss;
}
int bfs(vector<string>& words, string& target){
while(!q.empty()){
string tmp = q.front().first;
int count = q.front().second;
q.pop();
if(target == tmp)
return count;
for(int i=0;i<words.size();i++){
if(!visited[i]){
if(CalcDiff(tmp,words[i]) == 1){
visited[i] = 1;
//cout<<words[i] << " "<<count<<endl;
q.push({words[i],count+1});
}
}
}
}
return 0;
}
int solution(string begin, string target, vector<string> words) {
int answer = 0;
//error
if(find(words.begin(),words.end(),target) == words.end())
return 0;
q.push({begin,0});
answer = bfs(words,target);
return answer;
}