아래 모든 문제들은 프로그래머스에서 제공 되는 문제를 이용하였습니다, 감사합니다.
두 개의 단어 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 함수를 작성해주세요.
#include <string>
#include <vector>
#include <algorithm>
#include <queue>
using namespace std;
int dif_count(string s1, string s2)
{
int value = 0;
for(int i = 0; i < s1.size(); i++)
{
if (s1[i] != s2[i])
value++;
if (value == 2)
break;
}
return value;
}
int bfs(string begin, string target, vector<string> words, vector<int> visit)
{
pair<string, int> tmp(begin, 0);
queue<pair<string, int>> q;
q.push(tmp);
while(!q.empty())
{
tmp = q.front();
q.pop();
if(tmp.first == target)
return tmp.second;
for(int i = 0; i < words.size(); i++)
if(1 == dif_count(tmp.first,words[i]) && visit[i] == 0)
{
visit[i] = 1;
q.push(pair<string, int>(words[i], tmp.second + 1));
}
}
}
int solution(string begin, string target, vector<string> words) {
vector<int> visit (words.size(), 0);
if (!(*find(words.begin(), words.end(), target) == target))
return 0;
return bfs(begin, target, words,visit);
}