두 개의 단어 begin, target과 단어의 집합 words가 있습니다. 아래와 같은 규칙을 이용하여 begin에서 target으로 변환하는 가장 짧은 변환 과정을 찾으려고 합니다.
예를 들어 begin이 "hit", target가 "cog", words가 ["hot","dot","dog","lot","log","cog"]라면 "hit" -> "hot" -> "dot" -> "dog" -> "cog"와 같이 4단계를 거쳐 변환할 수 있습니다.
두 개의 단어 begin, target과 단어의 집합 words가 매개변수로 주어질 때, 최소 몇 단계의 과정을 거쳐 begin을 target으로 변환할 수 있는지 return 하도록 solution 함수를 작성해주세요.
| begin | target | words | return |
|---|---|---|---|
| "hit" | "cog" | ["hot", "dot", "dog", "lot", "log", "cog"] | 4 |
| "hit" | "cog" | ["hot", "dot", "dog", "lot", "log"] | 0 |
O(N^2)의 시간복잡도를 가지고, N은 최대 50개이기 때문에 알맞은 알고리즘으로 보인다.#include <string>
#include <vector>
#include <queue>
using namespace std;
struct node{
string str;
int count;
};
bool onlyOneDifferent(string str1, string str2){
int count = 0;
for(int i = 0; i < str1.size(); i++){
if(str1[i] != str2[i]){
count++;
}
}
if(count == 1){
return true;
}
return false;
}
int bfs(string begin, string target, vector<string>& words){
int n = words.size();
vector<bool> visited(n, false);
queue<node> Q;
Q.push({begin, 0});
while(!Q.empty()){
node Current = Q.front(); Q.pop();
for(int i = 0; i < n; i++){
if(!visited[i] && onlyOneDifferent(Current.str, words[i])){
if(target == words[i]){
return Current.count + 1;
}
visited[i] = true;
Q.push({words[i], Current.count + 1});
}
}
}
return 0;
}
int solution(string begin, string target, vector<string> words) {
int answer = bfs(begin, target, words);
return answer;
}